Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Descending order: Java Map

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 missing a small thing.

Link1: Sorting Map

But the issue I am running into is that by default this is sorted by ascending order by value. I want to order it by descending order:

So what I did was I created a class that implements a comparator

class MyComparator implements Comparator {     Map map;     public MyComparator(Map map) {         this.map = map;     }     public int compare(Object o1, Object o2) {         return ((Integer) map.get(o2)).compareTo((Integer) map.get(o1));     } } 

And then I pass my map to the treemap,

MyComparator comp = new MyComparator(myMap); Map<String, Integer> newMap = new TreeMap(comp); newMap.putAll(myMap); 

This seems like bad approach because I feel this is inefficient. Is there a way to change the solution in the link to do ordering on descending order by default.

like image 979
add-semi-colons Avatar asked Sep 20 '13 18:09

add-semi-colons


People also ask

How do you get descending order on TreeMap?

By default TreeMap elements in Java are sorted in ascending order of keys. However, we can create the TreeMap in reverse order using Collections. reverseOrder() method in Java and display the elements in descending order of keys.

How can we sort map in Java?

Sort HashMap by Values using Comparator Interface After that get the Set of elements from the Map and convert Set into the List. Use the Collections. sort(List) method to sort the list of elements by values by passing customized comparator. Now create a new LinkedHashMap and copy the sorted elements into that.

Can you sort a map by value in Java?

We can use the sort() method of the List interface to sort the elements of Map. The sort() method sorts the elements into ascending order and we specified the sort by value by using the comparingByValue() method.


2 Answers

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

Map<String, Integer> 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.

like image 155
Holger Avatar answered Oct 13 '22 22:10

Holger


    TreeMap<Long,String> treeMap = new TreeMap<Long,String>();      NavigableMap <Long, String> nmap = treeMap.descendingMap();      Set<Long, String> set = nmap.entrySet();      Iterator<Long, String> iterator = set.iterator(); 

now u can iterate over iterator and extract the value using iterator.hasNext() and iterator.next() methods ......

like image 26
Nilesh Jadav Avatar answered Oct 13 '22 22:10

Nilesh Jadav