In Java, a TreeMap is an implementation of the Map interface that uses a Red-Black tree to store key-value pairs in sorted order. This means that the keys are always sorted in a natural order, which makes TreeMap an ideal choice for scenarios where you need to retrieve elements i
Tweet
Here are some key features of a TreeMap in Java:
- Unique keys: Each key in a TreeMap must be unique. If you try to add a key that already exists in the TreeMap, the value associated with the key will be updated to the new value.
- Null keys and values: A TreeMap implementation does not allow null keys, but it allows null values.
- Sorted keys: The keys in a TreeMap are always sorted in a natural order. This means that you can retrieve elements in a sorted order, which is useful for scenarios where you need to iterate through the elements in a particular order.
Here’s an example of how to create and use a TreeMap in Java:
Tweet
import java.util.TreeMap;
import java.util.Map;
public class TreeMapExample {
public static void main(String[] args) {
// create a new TreeMap
Map<String, Integer> scores = new TreeMap<>();
// add some key-value pairs to the map
scores.put("Alice", 100);
scores.put("Bob", 90);
scores.put("Charlie", 80);
// get the value associated with a key
int aliceScore = scores.get("Alice");
System.out.println("Alice's score is " + aliceScore);
// iterate through the key-value pairs in the map
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
String name = entry.getKey();
int score = entry.getValue();
System.out.println(name + " scored " + score + " points.");
}
}
}
In this example, we create a new TreeMap and add some key-value pairs to it. We then retrieve the value associated with the "Alice" key using the get() method, and iterate through all the key-value pairs in the map using a for-each loop over the entrySet(). Since TreeMap is sorted in a natural order, the output of the program will be sorted by the keys in ascending order.