TreeMap sort by value

后端 未结 9 870
闹比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:49

    A lot of people hear adviced to use List and i prefer to use it as well

    here are two methods you need to sort the entries of the Map according to their values.

        static final Comparator> DOUBLE_VALUE_COMPARATOR = 
            new Comparator>() {
                @Override
                public int compare(Entry o1, Entry o2) {
                    return o1.getValue().compareTo(o2.getValue());
                }
            };
    
            static final List> sortHashMapByDoubleValue(HashMap temp)
            {
                Set> entryOfMap = temp.entrySet();
    
                List> entries = new ArrayList>(entryOfMap);
                Collections.sort(entries, DOUBLE_VALUE_COMPARATOR);
                return entries;
            }
    

提交回复
热议问题