Tue. Apr 16th, 2024

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

Like a HashMap, a TreeMap allows you to store key-value pairs and retrieve values based on their keys. However, unlike a HashMap, the keys in a TreeMap are always sorted. This means that TreeMap does not provide constant time complexity O(1) for basic operations like add, remove, and search, but instead provides logarithmic time complexity O(log n) for these operations.

Here are some key features of a TreeMap in Java:

  1. 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.
  2. Null keys and values: A TreeMap implementation does not allow null keys, but it allows null values.
  3. 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:

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.

By nerampo