Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

TreeMap

A map whose keys are always sorted.

Available since: Java 1.2

Syntax

public class TreeMap<K, V> implements NavigableMap<K, V>

Examples

Keys in alphabetical order:

void main() {
    Map<String, Integer> ages = new TreeMap<>();
    ages.put("Oleg", 25);
    ages.put("Anna", 31);
    ages.put("Ivan", 19);
    IO.println(ages);
}

Output:

{Anna=31, Ivan=19, Oleg=25}

Finding the nearest key, for example a discount by order total:

void main() {
    TreeMap<Integer, Integer> discounts = new TreeMap<>(Map.of(0, 0, 100, 5, 500, 10));
    IO.println(discounts.floorEntry(250).getValue() + "%");
    IO.println(discounts.firstKey() + " " + discounts.lastKey());
    IO.println(discounts.headMap(500));
}

Output:

5%
0 500
{0=0, 100=5}

Notes

Operations run in logarithmic time. Keys must be Comparable, or a Comparator must be passed to the constructor. A null key is not allowed. Navigation methods: floorKey(), ceilingKey(), headMap(), tailMap(), subMap().

See also

  • HashMap — A map backed by a hash table: fast lookup by key, no guaranteed order.
  • LinkedHashMap — A map that remembers the insertion order of keys.
  • TreeSet — A set that keeps its elements in sorted order.

Related recipes

In the tutorial

  • Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.

Thanks for reading!

Donate to the site — we work hard for you.