Java Program to Sort a Map By Values

To understand this example, you should have the knowledge of the following Java programming topics:


Example: Sort a map by values

import java.util.*;
import java.util.Map.Entry;

class Main {

  public static void main(String[] args) {

    // create a map and store elements to it
    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");

    // call the sortMap() method to sort the map
    Map<String, String> result = sortMap(capitals);

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

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

    // call the sort() method of Collections
    Collections.sort(capitalList, (l1, l2) -> l1.getValue().compareTo(l2.getValue()));

    // create a new map
    LinkedHashMap<String, String> result = new LinkedHashMap();

    // get entry from list to the map
    for (Map.Entry<String, String> entry : capitalList) {
      result.put(entry.getKey(), entry.getValue());
    }

    return result;
  }
}

Output

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 created a LinkedHashMap named capitals. The map stores countries and their respective capitals.

Here, we have created a sortMap() method that takes the map and returns the sorted map.

Inside the method, we first created a list named capitalList from the map capitals. We then use the sort() method of Collections to sort elements of the list.

The sort() method takes two parameters: list to be sorted and a comparator. In our case, the comparator is a lambda expression.

(l1, l2) -> l1.getValue().compareTo(l2.getValue())

Here, the lambda expression takes two adjacent element (l1 and l2) of the list. It then used the getValue() method to get the value and the compareTo() method to compare two values.

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

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

Did you find this article helpful?