TreeMap sort by value

后端 未结 9 1150
闹比i
闹比i 2020-11-22 02:44

I want to write a comparator that will let me sort a TreeMap by value instead of the default natural ordering.

I tried something like this, but can\'t find out what

9条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 03:28

    polygenelubricants answer is almost perfect. It has one important bug though. It will not handle map entries where the values are the same.

    This code:...

    Map nonSortedMap = new HashMap();
    nonSortedMap.put("ape", 1);
    nonSortedMap.put("pig", 3);
    nonSortedMap.put("cow", 1);
    nonSortedMap.put("frog", 2);
    
    for (Entry entry  : entriesSortedByValues(nonSortedMap)) {
        System.out.println(entry.getKey()+":"+entry.getValue());
    }
    

    Would output:

    ape:1
    frog:2
    pig:3
    

    Note how our cow dissapeared as it shared the value "1" with our ape :O!

    This modification of the code solves that issue:

    static > SortedSet> entriesSortedByValues(Map map) {
            SortedSet> sortedEntries = new TreeSet>(
                new Comparator>() {
                    @Override public int compare(Map.Entry e1, Map.Entry e2) {
                        int res = e1.getValue().compareTo(e2.getValue());
                        return res != 0 ? res : 1; // Special fix to preserve items with equal values
                    }
                }
            );
            sortedEntries.addAll(map.entrySet());
            return sortedEntries;
        }
    

提交回复
热议问题