Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

TreeMap — sorted maps and constructor references

TreeMap orders entries by key. Learn the difference between copying with TreeMap(Map), retaining a comparator with TreeMap(SortedMap), and using the constructor reference TreeMap::new.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

new TreeMap<K, V>(map)
Function<Map<K, V>, TreeMap<K, V>> copy = TreeMap::new;
Supplier<TreeMap<K, V>> empty = TreeMap::new;

java.util.TreeMap is a red-black-tree map ordered by keys, not insertion order. get, put, remove, and containsKey have guaranteed O(log n) cost.

TreeMap(Map) copies mappings using natural key order. TreeMap(SortedMap) retains the source ordering. Overload selection uses the argument's compile-time type.

TreeMap::new is a constructor reference, not an existing map. The target functional interface determines the overload: Function<Map<String, Integer>, TreeMap<String, Integer>> selects the copying constructor, while Supplier<TreeMap<String, Integer>> selects the no-argument constructor. A map is created only when apply or get is invoked.

Natural ordering requires mutually comparable keys implementing Comparable and forbids a null key. Comparison returning zero means the same key; ordering should be consistent with equals. TreeMap is not synchronized.

Examples

import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> source = Map.of("b", 2, "a", 1);
        TreeMap<String, Integer> direct = new TreeMap<>(source);
        Function<Map<String, Integer>, TreeMap<String, Integer>> copy = TreeMap::new;
        Supplier<TreeMap<String, Integer>> empty = TreeMap::new;

        System.out.println(direct);
        System.out.println(copy.apply(source));
        System.out.println(empty.get().isEmpty());
    }
}

Result

{a=1, b=2}
{a=1, b=2}
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources