Sorting LinkedHashMap by Keys in Java

In this blog post, we'll explore how to sort a LinkedHashMap by its keys in Java. A LinkedHashMap in Java is a hash table and linked list implementation of the Map interface, with predictable iteration order. 

Sorting becomes necessary when you need to process or display the entries of a LinkedHashMap in a specific, non-insertion order, such as alphabetical or numerical order based on keys. 

Sorting LinkedHashMap by Keys in Java

Here's the complete Java class that demonstrates how to sort a LinkedHashMap by its keys:
import java.util.*;
import java.util.stream.Collectors;

public class FruitSorter {

    // Method to sort LinkedHashMap by keys
    public static <K extends Comparable<? super K>, V> Map<K, V> sortMapByKey(LinkedHashMap<K, V> map) {
        return map.entrySet()
                  .stream()
                  .sorted(Map.Entry.comparingByKey())
                  .collect(Collectors.toMap(
                      Map.Entry::getKey,
                      Map.Entry::getValue,
                      (oldValue, newValue) -> oldValue, LinkedHashMap::new));
    }

    public static void main(String[] args) {
        // Creating and populating the LinkedHashMap
        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);

        // Displaying the original LinkedHashMap
        System.out.println("Original LinkedHashMap: " + fruits);

        // Sorting the LinkedHashMap by keys
        Map<String, Integer> sortedFruits = sortMapByKey(fruits);

        // Displaying the sorted LinkedHashMap
        System.out.println("Sorted LinkedHashMap by keys: " + sortedFruits);
    }
}

Output:

Original LinkedHashMap: {Apple=3, Orange=2, Banana=4, Grapes=1, Pineapple=5}
Sorted LinkedHashMap by keys: {Apple=3, Banana=4, Grapes=1, Orange=2, Pineapple=5}
We define a LinkedHashMap named fruits and populate it with fruit names as keys and integers as values. 

The sortMapByKey method sorts the map by its keys. It uses Java Streams to sort the entries based on keys and collects the results in a new LinkedHashMap

We first display the original map and then the sorted map. 

Sorting LinkedHashMap by Key in Java Using a Custom Comparator 

Here's the complete Java class demonstrating how to sort a LinkedHashMap by its keys using a custom comparator:
import java.util.*;
import java.util.stream.Collectors;

public class FruitSorter {

    // Custom Comparator
    public static Comparator<String> fruitNameComparator() {
        return (fruit1, fruit2) -> {
            // Custom comparison logic goes here
            // For example, sorting based on the length of the fruit name
            return Integer.compare(fruit1.length(), fruit2.length());
        };
    }

    // Method to sort LinkedHashMap by keys using a custom comparator
    public static <K, V> Map<K, V> sortMapByKeyWithComparator(LinkedHashMap<K, V> map, Comparator<K> comparator) {
        return map.entrySet()
                  .stream()
                  .sorted(Map.Entry.comparingByKey(comparator))
                  .collect(Collectors.toMap(
                      Map.Entry::getKey,
                      Map.Entry::getValue,
                      (oldValue, newValue) -> oldValue, LinkedHashMap::new));
    }

    public static void main(String[] args) {
        // Creating and populating the LinkedHashMap
        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);

        // Displaying the original LinkedHashMap
        System.out.println("Original LinkedHashMap: " + fruits);

        // Sorting the LinkedHashMap by keys using the custom comparator
        Map<String, Integer> sortedFruits = sortMapByKeyWithComparator(fruits, fruitNameComparator());

        // Displaying the sorted LinkedHashMap
        System.out.println("Sorted LinkedHashMap by custom comparator: " + sortedFruits);
    }
}

Output:

Original LinkedHashMap: {Apple=3, Orange=2, Banana=4, Grapes=1, Pineapple=5}
Sorted LinkedHashMap by custom comparator: {Apple=3, Grapes=1, Orange=2, Banana=4, Pineapple=5}
The fruitNameComparator method defines a custom comparator. In this example, it sorts fruit names based on their length. 

The sortMapByKeyWithComparator method sorts the map using the provided custom comparator. 

We show the original and the sorted map based on the custom sorting criteria.

Comments