Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting LinkedHashMap

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

like image 828
Ramin Avatar asked Aug 29 '12 18:08

Ramin


People also ask

Can LinkedHashMap be sorted?

LinkedHashMap just maintains insertion order. If you want to sort based on value, you may need to write your own comparator .

How do I sort keys in LinkedHashMap?

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.

Is LinkedHashMap keySet order?

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.


2 Answers

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()); } 
like image 196
Louis Wasserman Avatar answered Oct 06 '22 00:10

Louis Wasserman


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 -> ... ); 
like image 20
sprinter Avatar answered Oct 05 '22 23:10

sprinter