← Back to Advanced Java Course | Chapter 5: Collections Advanced | Lesson 1 of 4

Java TreeMap & TreeSet

TreeMap and TreeSet keep their items always in sorted order, like a shelf where books are kept alphabetized automatically. They also make it easy to find the next or previous item.
Syntax
java
TreeMap<KeyType, ValueType> map = new TreeMap<>();
TreeSet<Type> set = new TreeSet<>();  // both keep elements sorted

Introduction to TreeMap

A TreeMap is a Map implementation that keeps its keys continuously sorted, either by their natural ordering or by a custom Comparator you supply. Unlike a HashMap, iterating a TreeMap always visits keys in sorted order, at the cost of slightly slower average-case operations.

Example: Introduction to TreeMap

java
import java.util.TreeMap;
public class Main {
	public static void main(String[] args) {
		TreeMap<String, Integer> map = new TreeMap<>();
		map.put("banana", 2);
		map.put("apple", 1);
		map.put("cherry", 3);
		System.out.println(map); // iterates in sorted key order
	}
}

Navigating TreeMap Methods

TreeMap implements the NavigableMap interface, which adds a rich set of methods for finding the nearest matching key relative to a given value (like floorKey or ceilingKey), or for retrieving a sorted sub-range of the map's entries directly.

Example: Navigating TreeMap Methods

java
// Import java.util.TreeMap so it can be used by its short name
import java.util.TreeMap;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new TreeMap object and store it in map
		TreeMap<Integer, String> map = new TreeMap<>();
		map.put(10, "ten"); map.put(20, "twenty"); map.put(30, "thirty");
		// Print a line to the console
		System.out.println(map.floorKey(25));
		// Print a line to the console
		System.out.println(map.ceilingKey(25));
	}
}

Introduction to TreeSet

A TreeSet is the Set equivalent of a TreeMap: it automatically keeps its elements in ascending sorted order and, like every Set, rejects duplicate entries outright.

Example: Introduction to TreeSet

java
import java.util.TreeSet;
public class Main {
	public static void main(String[] args) {
		TreeSet<Integer> set = new TreeSet<>();
		set.add(5); set.add(1); set.add(3); set.add(1);
		System.out.println(set); // sorted, duplicates rejected
	}
}

Navigating TreeSet Methods

TreeSet implements the NavigableSet interface, offering the same kind of nearest-match and sub-range query methods that NavigableMap provides for TreeMap, letting you efficiently find elements around a given point without scanning the whole set.

Example: Navigating TreeSet Methods

java
// Import java.util.TreeSet so it can be used by its short name
import java.util.TreeSet;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new TreeSet object and store it in set
		TreeSet<Integer> set = new TreeSet<>();
		set.add(10); set.add(20); set.add(30);
		// Print a line to the console
		System.out.println(set.higher(15));
		// Print a line to the console
		System.out.println(set.headSet(25));
	}
}

Custom Sorting in Tree Collections

You can customize how elements are ordered in either Tree collection by passing a custom Comparator into its constructor at creation time, overriding the elements' natural ordering entirely, which is essential when the element type doesn't implement Comparable or you want a different order than its default.

Example: Custom Sorting in Tree Collections

java
// Import java.util.TreeSet so it can be used by its short name
import java.util.TreeSet;
// Import java.util.Comparator so it can be used by its short name
import java.util.Comparator;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new TreeSet object and store it in set
		TreeSet<String> set = new TreeSet<>(Comparator.reverseOrder());
		set.add("apple"); set.add("banana"); set.add("cherry");
		// Print a line to the console
		System.out.println(set);
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Adding a null key to a TreeMap or null to a TreeSet with natural ordering, which throws a NullPointerException.
  2. Storing objects that do not implement Comparable (and giving no Comparator), which throws a ClassCastException on the first insert.
  3. Using a Comparator that returns 0 for different objects, so a TreeSet treats them as duplicates and silently drops one.
🔒

Chapter Quiz — Complete all 4 topics to unlock

0/4 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.