1. Introduction

In Java, a HashMap does not guarantee any specific order of its elements. However, there might be scenarios where we need to sort a HashMap by its values. This can be achieved by converting the entrySet of the HashMap into a List and sorting the List using the sort method from the Collections class. In this tutorial, we will demonstrate how to sort a HashMap by its values.

2. Program Steps

1. Create a HashMap and populate it with some key-value pairs.

2. Convert the entrySet of the HashMap into a List of Map.Entry.

3. Sort the List using the sort method from the Collections class, providing a custom comparator to sort the entries by their values.

4. Create a LinkedHashMap and populate it with the sorted entries to maintain the order.

5. Iterate through the LinkedHashMap and print the sorted entries.

3. Code Program

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

public class SortHashMapByValues {

    public static void main(String[] args) {

        // Step 1: Create a HashMap and populate it with some key-value pairs
        Map<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("Banana", 3);
        unsortedMap.put("Apple", 1);
        unsortedMap.put("Cherry", 2);

        // Step 2: Convert the entrySet of the HashMap into a List of Map.Entry
        List<Map.Entry<String, Integer>> list = new ArrayList<>(unsortedMap.entrySet());

        // Step 3: Sort the List using the sort method from the Collections class
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });

        // Step 4: Create a LinkedHashMap and populate it with the sorted entries
        Map<String, Integer> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<String, Integer> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        // Step 5: Iterate through the LinkedHashMap and print the sorted entries
        System.out.println("HashMap after sorting by values:");
        for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output:

HashMap after sorting by values:
Apple: 1
Cherry: 2
Banana: 3

4. Step By Step Explanation

Step 1: We start by creating a HashMap named unsortedMap and populate it with some key-value pairs where the keys are of type String and the values are of type Integer.

Step 2: We convert the entrySet of the unsortedMap into a List of Map.Entry. This List contains the elements of the HashMap in the form of key-value pairs.

Step 3: The List is then sorted using the sort method from the Collections class. A custom comparator is provided to the sort method to ensure that the sorting is based on the values of the entries.

Step 4: After sorting the List, we create a LinkedHashMap named sortedMap and populate it with the sorted entries. The LinkedHashMap maintains the insertion order, which means it will keep the sorted order of the entries.

Step 5: Finally, we iterate through the LinkedHashMap and print the sorted key-value pairs to the console.