Java Treemap — Free Java Tutorial
Learn Java Treemap in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
TL;DR: Learn Java Treemap in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated
Java Treemap in Java
TreeMap<K,V> is a Map implementation that stores key-value pairs in sorted key order (natural order or custom Comparator). It uses a Red-Black tree internally.
All operations (put, get, remove, containsKey) run in O(log n) time — slower than HashMap (O(1)) but always sorted.
TreeMap provides navigation methods: firstKey(), lastKey(), headMap(toKey), tailMap(fromKey), subMap(from, to), floorKey(), ceilingKey().
Use TreeMap when you need keys in sorted order, or when you need range queries on keys. Use HashMap when order does not matter and you want speed.
Java Treemap — Syntax
TreeMap<String, Integer> map = new TreeMap<>();
map.put("banana", 2);
map.put("apple", 5);
map.put("cherry", 1);
// Iterates in key order: apple, banana, cherry
map.firstKey(); // "apple"
map.lastKey(); // "cherry"
map.headMap("cherry"); // keys < "cherry"
map.floorKey("b");
Learn Java Treemap step by step with Syllab's free interactive Java tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Java course →