Sort Map by Value in Java

1. Introduction

Sorting a Map by its values is a bit more complex than sorting by keys because Maps are inherently structured to allow fast access based on keys. However, there are scenarios where sorting a Map based on its values is necessary, such as when prioritizing entries based on their values. Java provides several ways to accomplish this, and this blog post will demonstrate how to sort a Map by its values using the Java Stream API for flexibility and control over the sorting process.

2. Program Steps

1. Create and populate a HashMap with unsorted values.

2. Convert the Map's entrySet to a Stream.

3. Sort the Stream by the Map's values.

4. Collect the result in a LinkedHashMap to maintain the sorted order.

5. Display the sorted Map.

3. Code Program

import java.util.*;
import java.util.stream.*;

public class SortMapByValue {
    public static void main(String[] args) {
        // Creating and populating a `HashMap`
        Map<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("Five", 5);
        unsortedMap.put("Seven", 7);
        unsortedMap.put("Two", 2);
        unsortedMap.put("One", 1);
        unsortedMap.put("Three", 3);

        // Displaying the original unsorted map
        System.out.println("Original map: " + unsortedMap);

        // Sorting the map by values
        LinkedHashMap<String, Integer> sortedMap = unsortedMap.entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (e1, e2) -> e1, LinkedHashMap::new));

        // Displaying the map sorted by values
        System.out.println("Map sorted by values: " + sortedMap);
    }
}

Output:

Original map: {One=1, Two=2, Three=3, Five=5, Seven=7}
Map sorted by values: {One=1, Two=2, Three=3, Five=5, Seven=7}

Explanation:

1. The program begins by creating a HashMap named unsortedMap and populating it with string keys and integer values. Unlike TreeMap, HashMap does not maintain any order.

2. To sort the map by values, the entrySet of the map is converted into a Stream using .entrySet().stream(). The Stream API provides a flexible way to sort data.

3. The stream is sorted based on the map's values using .sorted(Map.Entry.comparingByValue()). This method uses natural ordering of values for sorting.

4. The sorted stream is then collected into a LinkedHashMap using Collectors.toMap(). A LinkedHashMap is used because it maintains the order of elements as they are inserted. The parameters of Collectors.toMap() specify how to handle key-value pairs during the collection process.

5. Finally, the sorted map is displayed, showing that the entries have been ordered based on their values.

6. This example highlights the power of the Stream API in Java for manipulating collections, allowing for sorting a map by its values in a concise and readable manner.

Comments