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

import java.util.*;

public class SortMap {

    public static void main(String[] args) {

        LinkedHashMap<String, String> capitals = new LinkedHashMap<>();
        capitals.put("Nepal", "Kathmandu");
        capitals.put("India", "New Delhi");
        capitals.put("United States", "Washington");
        capitals.put("England", "London");
        capitals.put("Australia", "Canberra");

        Map<String, String> result = sortMap(capitals);

        for (Map.Entry<String, String> entry : result.entrySet())
        {
            System.out.print("Key: " + entry.getKey());
            System.out.println(" Value: " + entry.getValue());
        }
    }

    public static LinkedHashMap<String, String> sortMap(LinkedHashMap<String, String> map) {
        List<Map.Entry<String, String>> capitalList = new LinkedList<>(map.entrySet());

        Collections.sort(capitalList, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));

        LinkedHashMap<String, String> result = new LinkedHashMap<>();
        for (Map.Entry<String, String> entry : capitalList)
        {
            result.put(entry.getKey(), entry.getValue());
        }

        return result;
    }
}

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.