java中map的排序问题

java中Map排序问题

按key排序

public class MapSortDemo {

    public static void main(String[] args) {

        Map<String, String> map = new TreeMap<String, String>();

        map.put("KFC", "kfc");
        map.put("WNBA", "wnba");
        map.put("NBA", "nba");
        map.put("CBA", "cba");

        Map<String, String> resultMap = sortMapByKey(map);     
        for (Map.Entry<String, String> entry : resultMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }

    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, String> sortMap = new TreeMap<String, String>(
                new MapKeyComparator());

        sortMap.putAll(map);

        return sortMap;
    }
}

class MapKeyComparator implements Comparator<String>{

    @Override
    public int compare(String str1, String str2) {

        return str1.compareTo(str2);
    }
}

按value排序

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            Map map = new LinkedHashMap<>();
            String sentence = sc.nextLine();
            char[] arr = sentence.toCharArray();
            for(int i=0;iif((arr[i] >= 'A' && arr[i] <= 'Z') ||
                        (arr[i] >='a' && arr[i] <= 'z')||
                        arr[i] >= '1' && arr[i] <= '9' ||
                        arr[i]==' '){
                    if(map.get(arr[i]) != null){
                        map.put(arr[i], map.get(arr[i])+1);
                    }else{
                        map.put(arr[i], 1);
                    }
                }
            }
            // 转化为list
            List> entryList = new ArrayList>(
                    map.entrySet());
            //  public static  void sort(List list, Comparator c) 
            Collections.sort(entryList, new MapValueComparator());
            for (Map.Entry cc : entryList) {
                System.out.print(cc.getKey());
            }
        }

    }

    private static class MapValueComparator implements Comparator>{
        @Override
        public int compare(Map.Entry o1, Map.Entry o2) {
            if(o1.getValue() < o2.getValue())
                return 1;
            else if(o1.getValue() == o2.getValue())
                return o1.getKey()-(o2.getKey());
            else
                return -1;
        }
    }
}

你可能感兴趣的:(java)