Home › coding › java › java treemap

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.

✓ 100% Free ✓ No Login Needed ✓ NCERT / CBSE Aligned ✓ Download as PDF

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 Jul 14, 2026

🤖 Stuck on any question? Ask Syllab's free AI Tutor for a step-by-step explanation — instant, unlimited, no login.

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 →

Explore:

  • Syllabus
  • Practice
  • Mock Tests
  • NCERT Solutions
  • Coding
  • GK Quiz
  • Career Predictor
  • AI Tutor
  • Live Quiz
  • Doubt Solver
  • Microlearning
  • Free Alternatives
  • Kids Zone
  • Study Room
  • Calculators
  • Worksheets

Syllab.in — Free learning for Indian students, Class 1–12