Java Program to Sort a Map By Values

In this program, you’ll learn to sort a given map by values in Java.

Example: Sort a map by values

  1. import java.util.*;
  2. public class SortMap {
  3. public static void main(String[] args) {
  4. LinkedHashMap<String, String> capitals = new LinkedHashMap<>();
  5. capitals.put("Nepal", "Kathmandu");
  6. capitals.put("India", "New Delhi");
  7. capitals.put("United States", "Washington");
  8. capitals.put("England", "London");
  9. capitals.put("Australia", "Canberra");
  10. Map<String, String> result = sortMap(capitals);
  11. for (Map.Entry<String, String> entry : result.entrySet())
  12. {
  13. System.out.print("Key: " + entry.getKey());
  14. System.out.println(" Value: " + entry.getValue());
  15. }
  16. }
  17. public static LinkedHashMap<String, String> sortMap(LinkedHashMap<String, String> map) {
  18. List<Map.Entry<String, String>> capitalList = new LinkedList<>(map.entrySet());
  19. Collections.sort(capitalList, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));
  20. LinkedHashMap<String, String> result = new LinkedHashMap<>();
  21. for (Map.Entry<String, String> entry : capitalList)
  22. {
  23. result.put(entry.getKey(), entry.getValue());
  24. }
  25. return result;
  26. }
  27. }

When you run the program, the output will be:

Key: Australia Value: Canberra
Key: Nepal Value: Kathmandu
Key: England Value: London
Key: India Value: New Delhi
Key: United States Value: Washington

In the above program, we have a LinkedHashMap with countries and their respective capitals stored in a variable capitals.

We have a method sortMap() that takes a linked hash map and returns the sorted linked hash map.

Inside the method, we converted the hash map to a list capitalList. Then, we use sort() method which takes a list and a comparator.

In our case, the comparator is the lambda which compares (o1, o2) -> o1.getValue().compareTo(o2.getValue()) two values of the items in the list o1 and o2.

After the operation, we get the sorted list capitalList. Then, we simply convert the list to LinkedHashMap result and return it.

Back in the main() method, we loop through each item in the map and print its key and value.