Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to sort a map by key

Short answer

A TreeMap always keeps its keys sorted. Copy any Map into it:

void main() {
    Map<String, Integer> stock = Map.of("pears", 4, "apples", 10, "cherries", 7);
    IO.println(new TreeMap<>(stock));
}

Output:

{apples=10, cherries=7, pears=4}

Reverse order

Pass a comparator to the TreeMap constructor:

void main() {
    var stock = new TreeMap<String, Integer>(Comparator.reverseOrder());
    stock.putAll(Map.of("pears", 4, "apples", 10, "cherries", 7));
 
    IO.println(stock);
}

Output:

{pears=4, cherries=7, apples=10}

First and last key

A TreeMap can quickly find the outer and nearest keys:

void main() {
    var rates = new TreeMap<>(Map.of(0, "free", 100, "basic", 500, "pro"));
 
    IO.println(rates.firstKey());
    IO.println(rates.floorEntry(250).getValue());
}

Output:

0
basic

With a stream

If you do not need a TreeMap, sort the pairs in a stream:

void main() {
    Map<String, Integer> stock = Map.of("pears", 4, "apples", 10, "cherries", 7);
 
    stock.entrySet().stream()
            .sorted(Map.Entry.comparingByKey())
            .forEach(e -> IO.println(e.getKey() + " " + e.getValue()));
}

Output:

apples 10
cherries 7
pears 4

Common mistake

Sorting numbers stored as strings. Strings are compared character by character, so "10" comes before "9":

void main() {
    IO.println(new TreeMap<>(Map.of("9", "nine", "10", "ten", "100", "hundred")).keySet());
}

Output:

[10, 100, 9]

Store numeric keys as Integer.

Functions used in this recipe

  • TreeMap — A map whose keys are always sorted.
  • Map.Entry — A single key and value pair of a map.
  • Collectors.toMap() — A collector that builds a map from stream elements.

Thanks for reading!

Donate to the site — we work hard for you.