Java TreeMap & TreeSet
In this page:
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
// 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));
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
// 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));
}
}
Login to try C/C++/Java/PHP code in the editor
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
// 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);
}
}
Login to try C/C++/Java/PHP code in the editor
- Adding a
nullkey to aTreeMapornullto aTreeSetwith natural ordering, which throws aNullPointerException. - Storing objects that do not implement
Comparable(and giving no Comparator), which throws aClassCastExceptionon the first insert. - Using a Comparator that returns 0 for different objects, so a
TreeSettreats them as duplicates and silently drops one.
Chapter Quiz — Complete all 4 topics to unlock
0/4 topics done
Complete these topics first: