1

I am using function which returns key value pair in LinkedHashMap.

LinkedHashMap<Integer,String> lhm = new LinkedHashMap<Integer,String>();

  // Put elements to the map
  lhm.put(10001, "Stack");
  lhm.put(10002, "Heap");
  lhm.put(10003, "Args");
  lhm.put(10004, "Manus");
  lhm.put(10005, "Zorat");

Note: I cannot change LinkedHashMap to any other map in my code as the function is being used in several other functions.

I have also googled and tried to use TreeMap which gives us the desired result in ascending order. But, here in TreeMap key is in ascending order and not the values.

My requirement is mainly for values.

How can I get values in Ascending order.

Desired Output

10003, "Args"
10002, "Heap"
10004, "Manus"
10001, "Stack"
10005, "Zorat"

Thank you in advance !!!!

Tatkal
  • 568
  • 4
  • 9
  • 29
  • 1
    Possible duplicate of [Sort a Map by values (Java)](http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java) – vefthym May 04 '17 at 08:24
  • You just want to print it? You don't want to have a LinkedHashMap with the entries sorted by value? – Robin Topper May 04 '17 at 08:34
  • @RobinTopper its ok if i can get with LinkedHashMap entries sorted by value – Tatkal May 04 '17 at 08:55

4 Answers4

2

You need a comparator for this

  Comparator<Entry<String, String>> valueComparator = new 
                                  Comparator<Entry<String,String>>() { 
  @Override public int compare(Entry<String, String> e1, Entry<String, 
     String> e2) { 

     String v1 = e1.getValue(); String v2 = e2.getValue(); return 
     v1.compareTo(v2); 
 } 
};
Dishonered
  • 8,449
  • 9
  • 37
  • 50
1

You can do this with streams:

lhm.entrySet().stream().sorted(Map.Entry.comparingByValue())
    .forEach( (e)->System.out.println(e.getKey() + ", " + e.getValue()) );

Above will print exactly what you want.

LLL
  • 1,777
  • 1
  • 15
  • 31
0

This answer starts the same as this answer, but puts the sorted entries back into a LinkedHashMap:

LinkedHashMap<Integer,String> lhm2 = 
  lhm.entrySet().stream().sorted(Map.Entry.comparingByValue())
  .collect(Collectors.toMap(Entry::getKey, Entry::getValue,(a,b)->a, LinkedHashMap::new));

lhm2.forEach((k,v) -> System.out.println(k + ", " + v));
Community
  • 1
  • 1
Robin Topper
  • 2,295
  • 1
  • 17
  • 25
0
lhm.entrySet().stream()
.sorted(Map.Entry.comparingByValue().reversed())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));

This will sort your MAP in ascending order.

Amit Gujarathi
  • 1,090
  • 1
  • 12
  • 25