Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

TreeMap(): natural key ordering and grouping

`TreeMap()` creates an empty map that sorts keys by their natural order. Use `TreeMap::new` as the map supplier when `groupingBy` should return sorted group keys.

Version: Java SE 21

Syntax

import java.util.List;
import java.util.TreeMap;

TreeMap<Integer, String> map = new TreeMap<>();

// With java.util.stream.Collectors imported and a Stream<String> named words:
TreeMap<Integer, List<String>> groups = words.collect(
    Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()));

TreeMap() is the no-argument constructor of java.util.TreeMap. Calling new TreeMap<>() creates an empty map whose keys are visited in natural order, not insertion order. Keys must implement Comparable and be mutually comparable through compareTo; trying to insert an incompatible key throws ClassCastException. For Integer keys, natural order is ascending numeric order.

Without a comparator that accepts null, put(null, value) throws NullPointerException, even in an empty naturally ordered map. This restriction is on keys, not values: put(key, null) is valid for a valid key. The Comparator overload lets you choose a different order and accepts null keys only if the comparator handles them. Passing null to that overload selects natural ordering; it does not enable null keys.

In Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()), the first argument determines the key, the second supplies a fresh empty map, and the third collects each group's elements into a list. The target Supplier takes no arguments, so TreeMap::new selects the no-argument constructor here, like () -> new TreeMap<>(). Passing the reference does not create a map; invoking the supplier does. The map sorts the group keys, not the elements inside each list.

Examples

import java.util.List;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        TreeMap<Integer, String> labels = new TreeMap<>();
        labels.put(10, "ten");
        labels.put(2, "two");
        System.out.println(labels.keySet());

        try {
            labels.put(null, "missing");
        } catch (NullPointerException e) {
            System.out.println("NullPointerException");
        }

        TreeMap<Integer, List<String>> byLength = List.of("pear", "a", "to", "plum")
            .stream()
            .collect(Collectors.groupingBy(String::length, TreeMap::new,
                                           Collectors.toList()));
        System.out.println(byLength);
    }
}

Result

[2, 10]
NullPointerException
{1=[a], 2=[to], 4=[pear, plum]}

Although `10` is inserted before `2`, it appears after it. The second line comes from catching the exception raised by inserting a null key. The last line shows groups in ascending word length; `pear` and `plum` are in the same list.

Related lessons

  • Java · Lesson 20 · Advanced · Version: 2
  • Java · Lesson 42 · Intermediate · Version: 2

Sources