Sort Map by Value

Write a Java program that sorts the entries of a HashMap based on their values. Initialize a HashMap with string keys and integer values. Sort the entries based on values in ascending order and print the sorted entries.

Approach 1

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Initialize a HashMap with string keys and integer values
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("A", 11);
        hashMap.put("B", 10);
        hashMap.put("C", 9);

        // Sort the entries based on values in ascending order
        List<Map.Entry<String, Integer>> entryList = new ArrayList<>(hashMap.entrySet());
        entryList.sort(Map.Entry.comparingByValue());

        // Print the sorted entries
        System.out.println("Sorted Entries:");
        for (Map.Entry<String, Integer> entry : entryList) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

This program initializes a HashMap with string keys and integer values, then sorts the entries based on their values in ascending order using the Collections.sort() method with a custom comparator. Finally, it prints the sorted entries.

Approach 2

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Initialize a HashMap with string keys and integer values
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("A", 11);
        hashMap.put("B", 10);
        hashMap.put("C", 9);

        // Create a TreeMap to sort entries by values
        TreeMap<Integer, String> sortedMap = new TreeMap<>();

        // Populate the TreeMap with values as keys and corresponding keys as values
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            sortedMap.put(entry.getValue(), entry.getKey());
        }

        // Print the sorted entries
        System.out.println("Sorted Entries:");
        for (Map.Entry<Integer, String> entry : sortedMap.entrySet()) {
            System.out.println(entry.getValue() + ": " + entry.getKey());
        }
    }
}

In this approach, a TreeMap is used to sort the entries based on their values (now keys in the TreeMap). The values in the original HashMap become keys in the TreeMap, and the corresponding keys in the original HashMap become values in the TreeMap. This allows TreeMap's natural ordering to sort the entries based on their values. Finally, it prints the sorted entries.

Approach 3

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Initialize a HashMap with string keys and integer values
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("A", 11);
        hashMap.put("B", 10);
        hashMap.put("C", 9);

        // Sort the entries based on values using streams
        LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
        hashMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .forEachOrdered(entry -> sortedMap.put(entry.getKey(), entry.getValue()));

        // Print the sorted entries
        System.out.println("Sorted Entries:");
        sortedMap.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

In this approach, we use streams to sort the entries based on values. We first create a stream from the entry set of the HashMap, then use the sorted() method with a comparator that compares entries by their values. Finally, we collect the sorted entries into a LinkedHashMap, preserving the order of insertion, and print the sorted entries.

Approach 4

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Initialize a HashMap with string keys and integer values
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("A", 11);
        hashMap.put("B", 10);
        hashMap.put("C", 9);

        // Convert HashMap entries to a list
        List<Map.Entry<String, Integer>> entryList = new ArrayList<>(hashMap.entrySet());

        // Sort the list based on values
        Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
                return entry1.getValue().compareTo(entry2.getValue());
            }
        });

        // Create a new LinkedHashMap to preserve the insertion order
        LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<String, Integer> entry : entryList) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        // Print the sorted entries
        System.out.println("Sorted Entries:");
        for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

In this approach:

  1. We use the entrySet() method to obtain a set of entries from the HashMap.

  2. We use the stream() method to convert the set of entries into a stream of entries.

  3. We use the sorted() method to sort the entries based on their values using the comparingByValue() method.

  4. We use the forEachOrdered() method to insert the sorted entries into a new LinkedHashMap, preserving the order of insertion.

  5. Finally, we print the sorted entries using the forEach() method and lambda expressions.

Approach 5

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Initialize a HashMap with string keys and integer values
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("A", 11);
        hashMap.put("B", 10);
        hashMap.put("C", 9);

        // Sort the entries based on values using Java 8 streams and lambda expressions
        LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
        hashMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .forEachOrdered(entry -> sortedMap.put(entry.getKey(), entry.getValue()));

        // Print the sorted entries
        System.out.println("Sorted Entries:");
        sortedMap.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

In this approach:

  1. We use the entrySet() method to obtain a set of entries from the HashMap.

  2. We use the stream() method to convert the set of entries into a stream of entries.

  3. We use the sorted() method to sort the entries based on their values using the comparingByValue() method.

  4. We use the forEachOrdered() method to insert the sorted entries into a new LinkedHashMap, preserving the order of insertion.

  5. Finally, we print the sorted entries using the forEach() method and lambda expressions.

Approach 6

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Initialize a HashMap with string keys and integer values
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("A", 11);
        hashMap.put("B", 10);
        hashMap.put("C", 9);

        // Create a TreeMap with a custom comparator to sort by values
        TreeMap<String, Integer> sortedMap = new TreeMap<>(new ValueComparator(hashMap));

        // Put all entries from the HashMap to the TreeMap
        sortedMap.putAll(hashMap);

        // Print the sorted entries
        System.out.println("Sorted Entries:");
        sortedMap.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

// Custom comparator class to compare values in the HashMap
class ValueComparator implements Comparator<String> {
    HashMap<String, Integer> map;

    public ValueComparator(HashMap<String, Integer> map) {
        this.map = map;
    }

    @Override
    public int compare(String key1, String key2) {
        Integer value1 = map.get(key1);
        Integer value2 = map.get(key2);
        // Compare values in descending order
        return value1.compareTo(value2);
    }
}

In this approach:

  1. We create a custom ValueComparator class that implements the Comparator interface to compare values in the HashMap.

  2. We create a TreeMap and pass an instance of the ValueComparator class to its constructor. This TreeMap will sort entries based on values.

  3. We put all entries from the HashMap to the TreeMap using the putAll() method, which automatically sorts them based on the custom comparator.

  4. Finally, we print the sorted entries.

Last updated