Java - Different ways to sort a Map

Introduces various methods of sorting a HashMap or Map.

  • Using LinkedHashMap
  • Using TreeMap
  • Using List
  • Using Stream

For more information on sorting, see How to Sort with Comparator or How to Sort by Comparable for reference.

Sort using LinkedHashMap

LinkedHashMap is a class that guarantees the order entered into the Map. If you sort the HashMap in the desired order and input it back into the LinkedHashMap in this order, you can output it in the sorted order.

Sort by key

Just get Map.Entry as a list, sort it by key value, and add it to LinkedHashMap in the sorted order.

Here is the implemented code:

Map<String, String> map = new LinkedHashMap<>();
map.put("Nepal", "Kathmandu");
map.put("United States", "Washington");
map.put("India", "New Delhi");
map.put("England", "London");
map.put("Australia", "Canberra");

Map<String, String> result = sortMapByKey(map);
for (Map.Entry<String, String> entry : result.entrySet()) {
    System.out.println("Key: " + entry.getKey() + ", "
            + "Value: " + entry.getValue());
}


public static LinkedHashMap<String, String> sortMapByKey(Map<String, String> map) {
    List<Map.Entry<String, String>> entries = new LinkedList<>(map.entrySet());
    Collections.sort(entries, (o1, o2) -> o1.getKey().compareTo(o2.getKey()));

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

If you look at the results, they are sorted in ascending order based on the key (alphabetic order).

Key: Australia, Value: Canberra
Key: England, Value: London
Key: India, Value: New Delhi
Key: Nepal, Value: Kathmandu
Key: United States, Value: Washington

Sort by value

Just get Map.Entry as a list, sort it by value, and add it to the LinkedHashMap in the sorted order.

Here is the implemented code:

Map<String, String> map = new LinkedHashMap<>();
map.put("Nepal", "Kathmandu");
map.put("United States", "Washington");
map.put("India", "New Delhi");
map.put("England", "London");
map.put("Australia", "Canberra");

Map<String, String> result = sortMapByValue(map);
for (Map.Entry<String, String> entry : result.entrySet()) {
    System.out.println("Key: " + entry.getKey() + ", "
            + "Value: " + entry.getValue());
}


public static LinkedHashMap<String, String> sortMapByValue(Map<String, String> map) {
    List<Map.Entry<String, String>> entries = new LinkedList<>(map.entrySet());
    Collections.sort(entries, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));

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

If you look at the results, they are sorted in ascending order based on value (alphabetic order).

Key: Australia, Value: Canberra
Key: Nepal, Value: Kathmandu
Key: England, Value: London
Key: India, Value: New Delhi
Key: United States, Value: Washington

Sort using TreeMap

TreeMap is a class implemented to be sorted and saved by [Comparator] (/en/java-sorting-comparator/) set when adding items. So there is no need to reorder after adding values.

As in the code below, an object is created by passing a comparator as an argument of TreeMap.

System.out.println("3");
Comparator<String> comparator = (s1, s2)->s2.compareTo(s1);
Map<String, String> map = new TreeMap<>(comparator);
map.put("Nepal", "Kathmandu");
map.put("United States", "Washington");
map.put("India", "New Delhi");
map.put("England", "London");
map.put("Australia", "Canberra");

for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println("Key: " + entry.getKey() + ", "
            + "Value: " + entry.getValue());
}

If you print it out, it is sorted in reverse alphabetical order based on the key. (because I created the Comparator in descending order)

Key: United States, Value: Washington
Key: Nepal, Value: Kathmandu
Key: India, Value: New Delhi
Key: England, Value: London
Key: Australia, Value: Canberra

Since TreeMap does not sort values, it can be used only when sorting keys.

Sort using List

After importing keySet or values into a List, there is a way to sort them. If you need to sort only one of the two types, you can use this method.

Sort by key

The following code sorts a List containing keys in ascending order.

Map<String, String> map = new HashMap<>();
map.put("Nepal", "Kathmandu");
map.put("United States", "Washington");
map.put("India", "New Delhi");
map.put("England", "London");
map.put("Australia", "Canberra");

List<String> keyList = new ArrayList<>(map.keySet());
keyList.sort((s1, s2)->s1.compareTo(s2));
for (String key : keyList) {
    System.out.println("Key: " + key);
}

result

Key: Australia
Key: England
Key: India
Key: Nepal
Key: United States

Comparator (s1, s2)->s1.compareTo(s2) in the code above can be replaced with String::compareTo.

keyList.sort(String::compareTo);

Sort by value

The following code sorts a List containing values in ascending order.

Map<String, String> map = new HashMap<>();
map.put("Nepal", "Kathmandu");
map.put("United States", "Washington");
map.put("India", "New Delhi");
map.put("England", "London");
map.put("Australia", "Canberra");

List<String> valueList = new ArrayList<>(map.values());
valueList.sort(String::compareTo);
for (String value : valueList) {
    System.out.println("Value: " + value);
}

result

Value: Canberra
Value: Kathmandu
Value: London
Value: New Delhi
Value: Washington

Sort using Stream

You can also sort using a Stream.

The following code uses Stream to sort by value or key.

Map<String, String> map = new HashMap<>();
map.put("Nepal", "Kathmandu");
map.put("United States", "Washington");
map.put("India", "New Delhi");
map.put("England", "London");
map.put("Australia", "Canberra");

// sort by key
List<Map.Entry<String, String>> entries =
        map.entrySet().stream()
                    .sorted(Map.Entry.comparingByKey())
                    .collect(Collectors.toList());
for (Map.Entry<String, String> entry : entries) {
    System.out.println("Key: " + entry.getKey() + ", "
            + "Value: " + entry.getValue());
}

// sort by value
System.out.println();
entries = map.entrySet().stream()
        .sorted(Map.Entry.comparingByValue())
        .collect(Collectors.toList());
for (Map.Entry<String, String> entry : entries) {
    System.out.println("Key: " + entry.getKey() + ", "
            + "Value: " + entry.getValue());
}

result

Key: Australia, Value: Canberra
Key: England, Value: London
Key: India, Value: New Delhi
Key: Nepal, Value: Kathmandu
Key: United States, Value: Washington

Key: Australia, Value: Canberra
Key: Nepal, Value: Kathmandu
Key: England, Value: London
Key: India, Value: New Delhi
Key: United States, Value: Washington

You can directly output the items sorted by sorted() from the Stream, but we have made it return a List with collect().

Reference

codechachaCopyright ©2019 codechacha