How can I sort a LinkedHashMap based on its values given that the LinkedHashMap contains of String and Integer. So I need to sort it based on the Values which are Integers. Thanks a lot
LinkedHashMap just maintains insertion order. If you want to sort based on value, you may need to write your own comparator .
Sorting LinkedHashMap in descending order of keys : Descending order :- Implement Comparator interface while creating new TreeMap by providing reverse sorting logic. Finally put all entries of LinkedHashMap into TreeMap class using putAll() method.
A LinkedHashMap is the same as a HashMap , except that the LinkedHashMap maintains the insertion order, whereas the HashMap does not. Internally, the LinkedHashMap uses the doubly-linked list to maintain the insertion order.
List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b){ return a.getValue().compareTo(b.getValue()); } }); Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> entry : entries) { sortedMap.put(entry.getKey(), entry.getValue()); }
This is now quite a bit easier with Java 8 streams: you don't need the intermediate map to sort:
map.entrySet().stream() .sorted(Map.Entry.comparingByValue()) .forEach(entry -> ... );
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