Sorting LinkedHashMap by Values in Java

Sorting a LinkedHashMap by its values is a common requirement in Java programming. Unlike sorting by keys, sorting by values adds an additional layer of complexity. In this post, we'll explore different ways to achieve this, using practical examples.

Method 1: Using Stream API

The Stream API in Java 8 and later versions is a flexible way to sort a LinkedHashMap by its values. Here's how you can do it: 

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

public class FruitSorter {

    // Method to sort LinkedHashMap by values
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(LinkedHashMap<K, V> map) {
        return map.entrySet()
                  .stream()
                  .sorted(Map.Entry.comparingByValue())
                  .collect(Collectors.toMap(
                      Map.Entry::getKey,
                      Map.Entry::getValue,
                      (e1, e2) -> e1, LinkedHashMap::new));
    }

    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 3);
        fruits.put("Orange", 2);
        fruits.put("Banana", 4);
        fruits.put("Grapes", 1);
        fruits.put("Pineapple", 5);

        System.out.println("Original LinkedHashMap: " + fruits);
        System.out.println("Sorted LinkedHashMap by values: " + sortByValue(fruits));
    }
}

Output:

Original LinkedHashMap: {Apple=3, Orange=2, Banana=4, Grapes=1, Pineapple=5}
Sorted LinkedHashMap by values: {Grapes=1, Orange=2, Apple=3, Banana=4, Pineapple=5}

Method 2: Using Collections.sort with a Custom Comparator 

Another approach is to use a list of map entries and then sort this list using Collections.sort with a custom comparator.
import java.util.*;
import java.util.stream.Collectors;

public class FruitSorter {

    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueUsingList(LinkedHashMap<K, V> map) {
        List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
        list.sort(Map.Entry.comparingByValue());

        Map<K, V> result = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    public static void main(String[] args) {
        LinkedHashMap<String, Integer> fruits = new LinkedHashMap<>();
        fruits.put("Apple", 3);
        fruits.put("Orange", 2);
        fruits.put("Banana", 4);
        fruits.put("Grapes", 1);
        fruits.put("Pineapple", 5);

        System.out.println("Original LinkedHashMap: " + fruits);
        System.out.println("Sorted LinkedHashMap by values using list: " + sortByValueUsingList(fruits));
    }
}

Output:

Original LinkedHashMap: {Apple=3, Orange=2, Banana=4, Grapes=1, Pineapple=5}
Sorted LinkedHashMap by values using list: {Grapes=1, Orange=2, Apple=3, Banana=4, Pineapple=5}

Conclusion 

Sorting a LinkedHashMap by values can be achieved through various methods in Java. The choice of method often depends on the specific requirements of the task, such as the need for a custom sorting order or performance considerations for large datasets. 

Experiment with these techniques to find the best fit for your Java applications. Stay tuned for more Java programming insights!

Comments