Sorting Map By Keys in Java 8

In Java 8, you can easily sort a Map by its keys using the Stream API and lambda expressions. This guide will show you how to sort a Map by keys and provide examples to demonstrate the process.

Table of Contents

  1. Introduction
  2. Sorting a Map Using TreeMap
  3. Sorting a Map Using Streams
  4. Complete Example
  5. Conclusion

Introduction

A Map in Java is a collection that associates keys with values. Sometimes, you may need to sort a Map by its keys for easier data retrieval and display. Java 8's Stream API makes it straightforward to perform such sorting.

Sorting a Map Using TreeMap

One way to sort a Map by its keys is to use a TreeMap, which sorts entries based on the natural ordering of keys or by a specified comparator.

Example

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SortMapUsingTreeMap {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Banana", 1);
        map.put("Apple", 2);
        map.put("Cherry", 3);

        // Using TreeMap to sort the map by keys
        TreeMap<String, Integer> sorted = new TreeMap<>(map);
        System.out.println("Sorted Map: " + sorted);
    }
}

Output:

Sorted Map: {Apple=2, Banana=1, Cherry=3}

Sorting a Map Using Streams

Another way to sort a Map by its keys is to use the Stream API provided by Java 8. This method is more flexible and can be used to sort the map in various ways.

Example

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class SortMapUsingStreams {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Banana", 1);
        map.put("Apple", 2);
        map.put("Cherry", 3);

        // Using Stream API to sort the map by keys
        Map<String, Integer> sorted = map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));
        System.out.println("Sorted Map: " + sorted);
    }
}

Output:

Sorted Map: {Apple=2, Banana=1, Cherry=3}

Explanation

  • map.entrySet().stream(): Converts the map's entry set to a stream.
  • .sorted(Map.Entry.comparingByKey()): Sorts the entries by key.
  • .collect(Collectors.toMap(...)): Collects the sorted entries into a new LinkedHashMap to maintain the insertion order.

Complete Example

Here's a complete example that demonstrates both methods for sorting a Map by keys.

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class SortMapByKeysExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Banana", 1);
        map.put("Apple", 2);
        map.put("Cherry", 3);

        // Using TreeMap to sort the map by keys
        TreeMap<String, Integer> sortedTreeMap = new TreeMap<>(map);
        System.out.println("Sorted Map using TreeMap: " + sortedTreeMap);

        // Using Stream API to sort the map by keys
        Map<String, Integer> sortedStreamMap = map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));
        System.out.println("Sorted Map using Streams: " + sortedStreamMap);
    }
}

Output:

Sorted Map using TreeMap: {Apple=2, Banana=1, Cherry=3}
Sorted Map using Streams: {Apple=2, Banana=1, Cherry=3}

Conclusion

Sorting a Map by its keys in Java 8 can be easily achieved using either a TreeMap or the Stream API. The TreeMap approach is straightforward and sorts the map by natural key order or a custom comparator. The Stream API approach offers more flexibility and can be customized further. Both methods ensure the keys are sorted, making data retrieval and display easier.

Comments