Java TreeMap
In Java, the TreeMap
class is a sorted map implementation that is based on a red-black tree data structure. It implements the NavigableMap
interface and provides a fast and efficient way to store key-value pairs in a sorted order.
Here are some key features of TreeMap
:
TreeMap maintains the order of elements according to their natural ordering (if the keys are Comparable) or according to the custom Comparator provided at the time of creation.
TreeMap
provides O(log n) time complexity for basic operations such as insertion, deletion, and search.It does not allow null keys but allows null values.
TreeMap is not thread-safe. If multiple threads access a TreeMap concurrently and at least one of the threads modifies the map structurally, it must be synchronized externally.
The
TreeMap
class provides many methods to navigate and manipulate the map based on the keys, including methods inherited from theNavigableMap
interface such aslowerKey()
,higherKey()
,ceilingEntry()
,floorEntry()
, etc.
Here is an example of how to create a TreeMap and perform some basic operations:
import java.util.*; public class TreeMapExample { public static void main(String[] args) { // Creating a TreeMap TreeMap<Integer, String> treeMap = new TreeMap<>(); // Adding elements to TreeMap treeMap.put(2, "Two"); treeMap.put(1, "One"); treeMap.put(4, "Four"); treeMap.put(3, "Three"); // Displaying TreeMap System.out.println("TreeMap: " + treeMap); // Accessing values from TreeMap System.out.println("Value of key 1: " + treeMap.get(1)); // Removing elements from TreeMap treeMap.remove(2); System.out.println("TreeMap after removal of key 2: " + treeMap); // Navigating through TreeMap System.out.println("First key: " + treeMap.firstKey()); System.out.println("Last key: " + treeMap.lastKey()); System.out.println("Key less than 3: " + treeMap.lowerKey(3)); System.out.println("Key greater than 2: " + treeMap.higherKey(2)); } }
Output:
TreeMap: {1=One, 2=Two, 3=Three, 4=Four} Value of key 1: One TreeMap after removal of key 2: {1=One, 3=Three, 4=Four} First key: 1 Last key: 4 Key less than 3: 1 Key greater than 2: 3