53

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

Mike Causer
  • 8,196
  • 2
  • 43
  • 63
Ramin
  • 891
  • 2
  • 10
  • 16

4 Answers4

81
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());
}
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
48

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 -> ... );
sprinter
  • 27,148
  • 6
  • 47
  • 78
  • 1
    What's in those three dots? – Barracuda Dec 03 '19 at 20:39
  • Those three dots represent whatever you want to do with the sorted values. It might be to call another method, print them, collect them in a different map - whatever your problem requires. – sprinter Dec 04 '19 at 01:48
  • 2
    Why is this answer accepted and so highly ratet? It does not answer how to sort the map itself. It just tells how to process the contents of the map in a specific order. – Guardian667 Sep 08 '20 at 20:17
  • 1
    @Guardian667 Maps themselves cannot be sorted in place. That's quite clear in the documentation for the interface though some maps make guarantees of their order. I suspect OP and upvoters realised that and understood 'sorting the map based on its values' to mean using the entries in order of their values. No other interpretation of the question makes any sense. – sprinter Sep 08 '20 at 21:49
  • That's a valid suggestion. Thank you – Guardian667 Sep 10 '20 at 09:27
4

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

kosa
  • 65,990
  • 13
  • 130
  • 167
  • 1
    Brilliant, Yes, Thanks a lot, I did write my own comparator – Ramin Aug 29 '12 at 18:48
  • 1
    I don't think you need to write your own comparator. `Map.Entry.comparingByValue()` should generate one for you. And it can be reversed by `Collections.reverseOrder(Map.Entry.comparingByValue())`. – sprinter Jan 09 '15 at 12:16
  • @sprinter: What if the value is type of any custom object? – kosa Jan 09 '15 at 15:46
  • @Nambari Either have that type implement `Comparable` or provide a customer `Comparator` to `Map.Entry.comparingByValue`. – sprinter Jan 10 '15 at 04:51
  • @sprinter: Exactly, that is what this answer was about. – kosa Jan 11 '15 at 00:07
  • 1
    and how would you use that comparator? are you providing a different solutions from the others – Radu Simionescu Feb 15 '16 at 13:39
1
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;

public class HashMapTest {

public static void main(String[] args) {

    Map<String, Integer> map=new LinkedHashMap<String, Integer>();

    map.put("a", 11);
    map.put("B", 12);
    map.put("c", 3);
    map.put("d", 4);
    map.put("e", 5);
    map.put("f", 6);
    map.put("g", 7);
    map.put("h", 8);
    map.put("i", 9);
    map.put("j", 3);
    map.put("k", 2);
    map.put("l", 1);

    List<Map.Entry<String, Integer>> entries = new 
    ArrayList<Map.Entry<String, Integer>>(map.entrySet());
            Collections.sort(entries,new CustomizedHashMap());


            Map<String, Integer> sortedMap = new LinkedHashMap<String, 
   Integer>();
            for (Map.Entry<String, Integer> entry : entries) {
              sortedMap.put(entry.getKey(), entry.getValue());
              System.out.print( sortedMap.put(entry.getKey(), 
          entry.getValue())+"  ");
            }
     }
    }

 class CustomizedHashMap implements Comparator<Map.Entry<String, Integer>> {

  @Override
  public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
    // TODO Auto-generated method stub
    return -o1.getValue().compareTo(o2.getValue());
  }

}
Sachindra N. Pandey
  • 1,177
  • 17
  • 15