How to sort a treemap based on its values?

前端 未结 9 1029
萌比男神i
萌比男神i 2020-12-01 04:53

How can I sort a treemap using its values rather than the key?

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 05:17

    Try this. This sorts TreeMap values in ascending order, assuming that is how you want the values to be sorted.

    static  Map sortByValues(Map map) {
            List list = new ArrayList(map.entrySet());
    
            // copy Map to List to use Comparator
            Collections.sort(list, new Comparator() {
                public int compare(Object o1, Object o2) {
                    return ((Comparable) ((Map.Entry) o1).getValue()).compareTo(((Map.Entry) o2).getValue());
                }
            });
    
            // then copy List to LinkedHashMap as it preserves insertion order
            Map result = new LinkedHashMap();
            Iterator itr = list.iterator();
            while (itr.hasNext()) {
                Map.Entry m = (Map.Entry) itr.next();
                result.put(m.getKey(), m.getValue());
            }
    
            return result;
        }
    

提交回复
热议问题