In Java, TreeMap is a class that implements the SortedMap interface and provides a red-black tree-based implementation of a NavigableMap. It stores key-value pairs in a sorted order based on the natural ordering of the keys or a custom comparator. Here's when and why you would use a TreeMap:
Sorted and ordered data: If you need to maintain the elements in a sorted order based on the keys, TreeMap is a suitable choice. It automatically sorts the keys, allowing efficient retrieval of entries in a specific order.
Range operations: TreeMap provides methods to perform range operations, such as getting a sub-map of keys within a specific range or finding the nearest key greater or less than a given key.
Custom sorting: TreeMap allows you to define a custom comparator to sort the keys in a specific order. This can be useful when the natural ordering of the keys is not desirable.
Here's an example of how to use TreeMap in Java:
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
// Create a TreeMap
TreeMap<Integer, String> treeMap = new TreeMap<>();
// Add key-value pairs to the TreeMap
treeMap.put(3, "Apple");
treeMap.put(1, "Banana");
treeMap.put(2, "Orange");
// Iterate over the TreeMap entries
for (var entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
// Get the first and last keys
int firstKey = treeMap.firstKey();
int lastKey = treeMap.lastKey();
System.out.println("First key: " + firstKey); // Output: 1
System.out.println("Last key: " + lastKey); // Output: 3
// Get a sub-map of keys within a range
TreeMap<Integer, String> subMap = treeMap.subMap(1, 3);
System.out.println("Sub-map: " + subMap); // Output: {1=Banana, 2=Orange}
// Get the nearest key greater or less than a given key
int greaterKey = treeMap.higherKey(2);
int lowerKey = treeMap.lowerKey(2);
System.out.println("Greater key: " + greaterKey); // Output: 3
System.out.println("Lower key: " + lowerKey); // Output: 1
}
}
No comments:
Post a Comment