Skip to content

Java TreeMap

It as a magical forest where each tree is meticulously arranged according to its height. Similarly, a Java TreeMap is a collection class that stores key-value pairs in a sorted order based on the keys. It's like having a neatly organized library where books are arranged alphabetically by their titles.

Now, let's dive deeper into the realm of TreeMap and see how it works its wonders:

  1. Sorted Order: One of the most fascinating features of TreeMap is its ability to maintain elements in a sorted order based on their keys. Whether you're storing names, numbers, or any other data, TreeMap ensures that they're always arranged in ascending order.

  2. Efficient Retrieval: Need to find a specific element in your collection quickly? TreeMap's binary search tree structure allows for efficient retrieval of elements based on their keys. It's like having a well-marked trail through the forest, making it easy to find your way around.

  3. Dynamic Updates: As your collection grows and evolves, TreeMap gracefully adjusts itself to accommodate new elements while preserving its sorted order. Whether you're adding, removing, or updating elements, TreeMap ensures that your collection remains organized at all times.

  4. Navigable Interface: TreeMap also provides a navigable interface, offering methods for navigating the collection in various ways. Whether you need to find the first or last element, or iterate over a subrange of elements, TreeMap has got you covered.

Now, let's take a stroll through a simple example to see TreeMap in action:

java
import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        // Create a TreeMap to store student scores
        TreeMap<String, Integer> studentScores = new TreeMap<>();

        // Add some student scores to the TreeMap
        studentScores.put("Alice", 85);
        studentScores.put("Bob", 92);
        studentScores.put("Charlie", 78);
        studentScores.put("Diana", 95);

        // Print the student scores in sorted order
        System.out.println("Student Scores:");
        for (String name : studentScores.keySet()) {
            System.out.println(name + ": " + studentScores.get(name));
        }
    }
}

In this example, we've created a TreeMap to store student scores, where the student names are the keys and their scores are the values. As we add elements to the TreeMap, it automatically sorts them based on the keys (student names), allowing us to print the scores in alphabetical order.

Creating a TreeMap

To begin our adventure, let's create a TreeMap and populate it with some key-value pairs:

java
import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> ages = new TreeMap<>();

        ages.put("Alice", 25);
        ages.put("Bob", 30);
        ages.put("Charlie", 35);
    }
}

Here, we've created a TreeMap called ages that maps names (keys) to ages (values). The TreeMap automatically sorts the entries based on the keys in ascending order.

Accessing and Modifying Elements

Now that we have our TreeMap, let's retrieve and modify some elements:

java
public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> ages = new TreeMap<>();

        ages.put("Alice", 25);
        ages.put("Bob", 30);
        ages.put("Charlie", 35);

        System.out.println("Alice's age: " + ages.get("Alice")); // Output: Alice's age: 25

        ages.put("Alice", 26); // Update Alice's age
        System.out.println("Updated Alice's age: " + ages.get("Alice")); // Output: Updated Alice's age: 26
    }
}

Here, we retrieve Alice's age using ages.get("Alice") and then update it by putting a new value with the same key.

One of the joys of TreeMap is its ability to navigate through the entries:

java
public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> ages = new TreeMap<>();

        ages.put("Alice", 25);
        ages.put("Bob", 30);
        ages.put("Charlie", 35);

        System.out.println("First person: " + ages.firstKey()); // Output: First person: Alice
        System.out.println("Last person: " + ages.lastKey());   // Output: Last person: Charlie

        System.out.println("Person younger than Bob: " + ages.higherKey("Bob")); // Output: Person younger than Bob: Charlie
    }
}

Here, we use methods like firstKey() and lastKey() to find the first and last entries, and higherKey("Bob") to find the key that comes after "Bob".

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.