TreeMap Implemented with Red-Black Tree
The TreeMap class in Java is an ordered Map collection implemented using a red-black tree. It resides in the java.util package and implements the SortedMap interface, allowing sorting based on the natural ordering of keys or a specified comparator.
Key characteristics of the TreeMap class include:
- Implementation based on Red-Black Tree: The
TreeMapclass is implemented using a red-black tree, enabling efficient insertion, deletion, and lookup operations. - Ordering: Elements within the
TreeMapare sorted according to the natural ordering of their keys or a specified comparator, facilitating convenient range queries and sorting operations. - Thread-Unsafe: The
TreeMapclass is not thread-safe; if used in a multi-threaded environment, additional synchronization measures must be implemented.
The TreeMap class provides multiple constructors to create an empty TreeMap object or a TreeMap object with a specified comparator. It also offers various methods for adding, removing, retrieving, and modifying elements, some of which are similar to those in the Map interface.
Key methods of the TreeMap class include:
- put() method: Adds a key-value pair to the
TreeMapobject. - remove() method: Removes the key-value pair associated with a specified key from the
TreeMapobject. - get() method: Retrieves the value associated with a specified key in the
TreeMapobject. - size() method: Returns the number of key-value mappings in the
TreeMapobject. - clear() method: Removes all key-value mappings from the
TreeMapobject.
// Example demonstrating basic operations on a TreeMap
import java.util.*;
public class TreeMapExample {
public static void main(String[] args) {
// Create an empty TreeMap using default natural ordering
TreeMap<String, Integer> map = new TreeMap<>();
// Add key-value pairs
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);
// Retrieve value by key
Integer val = map.get("banana");
System.out.println(val); // Output: 2
// Get the size of the map
System.out.println(map.size()); // Output: 3
// Remove a specific entry
map.remove("apple");
// Clear all entries
map.clear();
}
}
| Method | Description |
|---|---|
put(K key, V value) |
Associates the specified key with the specified value in this map. |
remove(Object key) |
Removes and returns the value associated with the specified key. |
get(Object key) |
Returns the value to which the specified key is mapped, or null if there is no mapping for the key. |
size() |
Returns the number of key-value mappings in this map. |
clear() |
Removes all of the mappings from this map. |