A TreeMap in Java is a part of the java.util package that implements the Map interface. It stores key-value pairs in a sorted order using either a natural or custom comparator.
- TreeMap internally uses a Red-Black Tree for efficient sorting.
- Provides O(log n) time for insertion, deletion and lookup.
- TreeMap does not allow null keys, but allows null values.
import java.util.Map;
import java.util.TreeMap;
public class TreeMapCreation {
public static void main(String args[]){
// Create a TreeMap of Strings (keys) and Integers
// (values)
TreeMap<String, Integer> tm = new TreeMap<>();
System.out.println("TreeMap elements: " + tm);
}
}
Output
TreeMap elements: {}