Sorting Descending order: Java Map

前端 未结 5 1868
不思量自难忘°
不思量自难忘° 2020-12-05 04:28

What I want to do is sort a map by value. I went over many questions that are available on the stackoverflow site and found out following solution that does what I want but

5条回答
  •  既然无缘
    2020-12-05 04:55

    You should use new TreeMap<>(Collections.reverseOrder());.

    Map newMap = new TreeMap<>(Collections.reverseOrder());
    newMap.putAll(myMap);
    

    or to reverse an existing comparator like the value-comparator Collections.reverseOrder(comparator). It works like your approach swapping the two objects before invoking compare/compareTo.

提交回复
热议问题