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.
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.
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.
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.
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
.
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 ......
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With