1

This is the code that I have:

Map<Integer,String> map = new HashMap<>();
map.put(23,"Nitin");
map.put(45,"Kapil");
map.put(20, "Sam");
map.put(18,"Adam");
for(Map.Entry m:map.entrySet()){
    System.out.println(m.getValue()+":"+m.getValue());
}

But I cannot possible order the data, I need to sort this hash map by value (Name).

Input: Map<Age,Name>

23, Nitin
45, Kapil
20, Sam
18, Adam

Output:

18, Adam
45, Kapil
23, Nitin
20, Sam
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
He Cris
  • 45
  • 6

1 Answers1

0

You can just use Java Streams to do this and sort the map my value:

Map<Integer, String> sorted = map.entrySet().stream()
        .sorted(Map.Entry.comparingByValue())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (s1, s2) -> s1, LinkedHashMap::new));

sorted.forEach((i, s) -> System.out.println(i + ": " + s));

A LinkedHashMap will preserve the order in which the keys are added into the map.

The result would be this:

18: Adam
45: Kapil
23: Nitin
20: Sam

If you want to reverse the order of the values you can use Comparator.reversed():

Map<Integer, String> sorted = map.entrySet().stream()
        .sorted(Map.Entry.<Integer, String>comparingByValue().reversed())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (s1, s2) -> s1, LinkedHashMap::new));
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56