How do I sort entries of a map by its keys or values?

To sort the entries of a map by keys or values in Java, you can convert your Map to a Stream, sort it, and then collect it back into a Map.

Here’s an example of sorting by keys:

package org.kodejava.util;

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

public class MapSortComparingByKey {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 10);
        map.put("Orange", 20);
        map.put("Banana", 30);

        Map<String, Integer> sortedByKey = map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new
                ));

        sortedByKey.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
    }
}

Output:

Key: Apple, Value: 10
Key: Banana, Value: 30
Key: Orange, Value: 20

In the example map.entrySet().stream() creates a Stream consisting of the entries in the map. The sorted(Map.Entry.comparingByKey()) method sorts the entries based on keys. The sorted entries are collected back into a new LinkedHashMap (which maintains the order of its elements).

You can sort by values in a similar way:

package org.kodejava.util;

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

public class MapSortComparingByValue {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 10);
        map.put("Orange", 20);
        map.put("Banana", 30);

        Map<String, Integer> sortedByValue = map.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new
                ));

        sortedByValue.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
    }
}

Output:

Key: Banana, Value: 30
Key: Orange, Value: 20
Key: Apple, Value: 10

In this example, sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) sorts the entries based on values in descending order. The reversed() method is used to reverse the natural ordering. If you want to sort in ascending order, omit the reversed() call.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.