A TreeMap
is part of the Java Collections Framework and implements the NavigableMap
interface, which means it is a type of map that stores data in a sorted order. It is a Red-Black tree-based implementation of the Map
interface, ensuring that its entries are ordered based on their keys.
Features
- Sorted Order: A
TreeMap
automatically sorts the keys in ascending order, using either the natural ordering of the keys or a custom comparator. - No Null Keys: Unlike
HashMap
,TreeMap
does not allownull
keys. However, it can containnull
values. - Fast Lookup and Updates: Like other map types,
TreeMap
provides efficient lookup, insertion, and removal operations. The time complexity for these operations is O(log n) due to the underlying Red-Black tree structure.
Common Methods
- put(K key, V value): Adds a key-value pair to the map. If the key already exists, it updates the value.
- get(Object key): Retrieves the value associated with the specified key.
- remove(Object key): Removes the key-value pair associated with the specified key.
- size(): Returns the number of key-value pairs in the map.
- firstKey(): Returns the first (lowest) key in the map.
- lastKey(): Returns the last (highest) key in the map.
- subMap(K fromKey, K toKey): Returns a view of the portion of the map whose keys range from
fromKey
totoKey
.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
import java.util.*; public class TreeMapExample { public static void main(String[] args) { // Creating a TreeMap TreeMap<Integer, String> treeMap = new TreeMap<>(); // 1. Adding key-value pairs using put() treeMap.put(1, "One"); treeMap.put(3, "Three"); treeMap.put(2, "Two"); treeMap.put(5, "Five"); treeMap.put(4, "Four"); // 2. Displaying the TreeMap System.out.println("TreeMap after put operations: " + treeMap); // 3. Retrieving a value using get() System.out.println("Value for key 3: " + treeMap.get(3)); // Output: Three // 4. Checking if a key exists using containsKey() System.out.println("Does key 4 exist? " + treeMap.containsKey(4)); // Output: true // 5. Checking if a value exists using containsValue() System.out.println("Does value 'One' exist? " + treeMap.containsValue("One")); // Output: true // 6. Removing a key-value pair using remove() treeMap.remove(2); System.out.println("TreeMap after removing key 2: " + treeMap); // 7. Getting the first and last keys using firstKey() and lastKey() System.out.println("First key: " + treeMap.firstKey()); // Output: 1 System.out.println("Last key: " + treeMap.lastKey()); // Output: 5 // 8. Using subMap() to get a portion of the TreeMap SortedMap<Integer, String> subMap = treeMap.subMap(2, 5); System.out.println("SubMap from key 2 to 5: " + subMap); // 9. Getting the size of the TreeMap System.out.println("Size of TreeMap: " + treeMap.size()); // Output: 4 // 10. Iterating through the TreeMap System.out.println("Iterating through TreeMap:"); for (Map.Entry<Integer, String> entry : treeMap.entrySet()) { System.out.println(entry.getKey() + " => " + entry.getValue()); } // 11. Updating a value for an existing key using put() treeMap.put(3, "Updated Three"); System.out.println("TreeMap after updating key 3: " + treeMap); } } //Output TreeMap after put operations: {1=One, 2=Two, 3=Three, 4=Four, 5=Five} Value for key 3: Three Does key 4 exist? true Does value 'One' exist? true TreeMap after removing key 2: {1=One, 3=Three, 4=Four, 5=Five} First key: 1 Last key: 5 SubMap from key 2 to 5: {3=Three, 4=Four} Size of TreeMap: 4 Iterating through TreeMap: 1 => One 3 => Three 4 => Four 5 => Five TreeMap after updating key 3: {1=One, 3=Updated Three, 4=Four, 5=Five} |
Use Cases
- When you need a sorted map of key-value pairs.
- For range queries (e.g., find all keys between 5 and 20).
- In applications where you frequently use navigation methods like
floorKey()
orceilingKey()
. - Ideal for database indexes or caching systems where sorted access is essential.