Java TreeMap Methods Tutorial with Examples

TreeMap is a part of the Java Collections Framework and provides an implementation of the NavigableMap interface. It is used to store key-value pairs in a sorted order, based on the natural ordering of its keys or by a custom comparator. This tutorial will cover all methods of TreeMap with examples and outputs, highlighting key points, use cases, best practices, performance considerations, and a real-time example with CRUD operations.

Table of Contents

  1. Introduction
  2. Key Points
  3. TreeMap Methods
    • put()
    • putAll()
    • get()
    • remove()
    • clear()
    • size()
    • isEmpty()
    • containsKey()
    • containsValue()
    • keySet()
    • values()
    • entrySet()
    • firstKey()
    • lastKey()
    • lowerKey()
    • higherKey()
    • floorKey()
    • ceilingKey()
    • pollFirstEntry()
    • pollLastEntry()
    • forEach()
    • replace()
    • compute()
    • computeIfAbsent()
    • computeIfPresent()
    • merge()
  4. Use Cases
  5. Best Practices
  6. Performance Considerations
  7. Real-time Example with CRUD Operations
  8. Conclusion

1. Introduction

A TreeMap in Java is a part of the Java Collections Framework and provides a way to manage key-value pairs in a sorted order. It is found in the java.util package and is backed by a TreeMap, ensuring that elements are stored in ascending order based on the natural ordering of the keys or by a custom comparator provided at map creation time.

2. Key Points

  • TreeMap allows null values but does not allow null keys.
  • It maintains elements in ascending order based on the natural ordering of keys or a custom comparator.
  • It is not synchronized.
  • It provides logarithmic time performance for basic operations like put, get, and remove.

3. TreeMap Methods

3.1. put()

The put() method is used to insert key-value pairs into the TreeMap.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits);
    }
}

Output:

{Apple=50, Banana=30, Mango=20}

3.2. putAll()

The putAll() method adds all key-value pairs from another map to the TreeMap.

Example:

import java.util.TreeMap;
import java.util.Map;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);

        Map<String, Integer> moreFruits = new TreeMap<>();
        moreFruits.put("Mango", 20);
        moreFruits.put("Orange", 40);

        fruits.putAll(moreFruits);
        System.out.println(fruits);
    }
}

Output:

{Apple=50, Banana=30, Mango=20, Orange=40}

3.3. get()

The get() method retrieves the value associated with the specified key.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits.get("Banana")); // 30
    }
}

Output:

30

3.4. remove()

The remove() method removes the key-value pair associated with the specified key.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        fruits.remove("Banana");
        System.out.println(fruits); // {Apple=50, Mango=20}
    }
}

Output:

{Apple=50, Mango=20}

3.5. clear()

The clear() method removes all key-value pairs from the TreeMap.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        fruits.clear();
        System.out.println(fruits); // {}
    }
}

Output: ``{}


### 3.6. size()
The `size()` method returns the number of key-value pairs in the `TreeMap`.

**Example:**
```java
import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits.size()); // 3
    }
}

Output:

3

3.7. isEmpty()

The isEmpty() method checks if the TreeMap is empty.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        System.out.println(fruits.isEmpty()); // true
        fruits.put("Apple", 50);
        System.out.println(fruits.isEmpty()); // false
    }
}

Output:

true
false

3.8. containsKey()

The containsKey() method checks if the TreeMap contains a specified key.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        System.out.println(fruits.containsKey("Banana")); // true
        System.out.println(fruits.containsKey("Mango")); // false
    }
}

Output:

true
false

3.9. containsValue()

The containsValue() method checks if the TreeMap contains a specified value.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        System.out.println(fruits.containsValue(30)); // true
        System.out.println(fruits.containsValue(20)); // false
    }
}

Output:

true
false

3.10. keySet()

The keySet() method returns a set view of the keys contained in the TreeMap.

Example:

import java.util.TreeMap;
import java.util.Set;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        Set<String> keys = fruits.keySet();
        System.out.println(keys); // [Apple, Banana, Mango]
    }
}

Output:

[Apple, Banana, Mango]

3.11. values()

The values() method returns a collection view of the values contained in the TreeMap.

Example:

import java.util.TreeMap;
import java.util.Collection;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        Collection<Integer> values = fruits.values();
        System.out.println(values); // [50, 30, 20]
    }
}

Output:

[50, 30, 20]

3.12. entrySet()

The entrySet() method returns a set view of the mappings contained in the TreeMap.

Example:

import java.util.TreeMap;
import java.util.Set;
import java.util.Map.Entry;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        Set<Entry<String, Integer>> entries = fruits.entry

Set();
        for (Entry<String, Integer> entry : entries) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

Output:

Apple = 50
Banana = 30
Mango = 20

3.13. firstKey()

The firstKey() method returns the first (lowest) key currently in the TreeMap.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits.firstKey()); // Apple
    }
}

Output:

Apple

3.14. lastKey()

The lastKey() method returns the last (highest) key currently in the TreeMap.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits.lastKey()); // Mango
    }
}

Output:

Mango

3.15. lowerKey()

The lowerKey() method returns the greatest key strictly less than the given key, or null if there is no such key.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits.lowerKey("Banana")); // Apple
    }
}

Output:

Apple

3.16. higherKey()

The higherKey() method returns the least key strictly greater than the given key, or null if there is no such key.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits.higherKey("Banana")); // Mango
    }
}

Output:

Mango

3.17. floorKey()

The floorKey() method returns the greatest key less than or equal to the given key, or null if there is no such key.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits.floorKey("Banana")); // Banana
    }
}

Output:

Banana

3.18. ceilingKey()

The ceilingKey() method returns the least key greater than or equal to the given key, or null if there is no such key.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        System.out.println(fruits.ceilingKey("Banana")); // Banana
    }
}

Output:

Banana

3.19. pollFirstEntry()

The pollFirstEntry() method removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.

Example:

import java.util.TreeMap;
import java.util.Map.Entry;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        Entry<String, Integer> firstEntry = fruits.pollFirstEntry();
        System.out.println(firstEntry); // Apple=50
        System.out.println(fruits); // {Banana=30, Mango=20}
    }
}

Output:

Apple=50
{Banana=30, Mango=20}

3.20. pollLastEntry()

The pollLastEntry() method removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.

Example:

import java.util.TreeMap;
import java.util.Map.Entry;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        Entry<String, Integer> lastEntry = fruits.pollLastEntry();
        System.out.println(lastEntry); // Mango=20
        System.out.println(fruits); // {Apple=50, Banana=30}
    }
}

Output:

Mango=20
{Apple=50, Banana=30}

3.21. forEach()

The forEach() method performs the given action for each entry in the TreeMap.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.put("Mango", 20);
        fruits.forEach((key, value) -> System.out.println(key + " = " + value));
    }
}

Output:

Apple = 50
Banana = 30
Mango = 20

3.22. replace()

The replace() method replaces the entry for the specified key only if it is currently mapped to some value.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.replace("Banana", 40);
        System.out.println(fruits); // {Apple=50, Banana=40, Mango=20}
    }
}

Output:

{Apple=50, Banana=40, Mango=20}

3.23. compute()

The compute() method computes a new mapping for the specified key and its current mapped value (or null if there is no current mapping).

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.compute("Banana", (key, value) -> (value == null) ? 40 : value + 10);
        System.out.println(fruits); // {Apple=50, Banana=40, Mango=20}
    }
}

Output:

{Apple=50, Banana=40, Mango=20}

3.24. computeIfAbsent()

The computeIfAbsent() method computes a mapping for the specified key if it is not already present.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.computeIfAbsent("Mango", key -> 20);
        System.out.println(fruits); // {Apple=50, Banana=30, Mango=20}
    }
}

Output:

{Apple=50, Banana=30, Mango=20}

3.25. computeIfPresent()

The computeIfPresent() method computes a new mapping for the specified key if it is currently present.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.computeIfPresent("Banana", (key, value) -> value + 10);
        System.out.println(fruits); // {Apple=50, Banana=40, Mango=20}
    }
}

Output:

{Apple=50, Banana=40, Mango=20}

3.26. merge()

The merge() method merges the

specified value with the existing value associated with the specified key.

Example:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> fruits = new TreeMap<>();
        fruits.put("Apple", 50);
        fruits.put("Banana", 30);
        fruits.merge("Banana", 20, (oldValue, newValue) -> oldValue + newValue);
        System.out.println(fruits); // {Apple=50, Banana=50, Mango=20}
    }
}

Output:

{Apple=50, Banana=50, Mango=20}

4. Use Cases

  • Sorted collections: Storing key-value pairs in a sorted order based on keys.
  • Database representation: Representing tables with rows as key-value pairs with natural order.
  • Configuration settings: Storing application settings as key-value pairs with natural order.

5. Best Practices

  • Use appropriate initial capacity: If the size of the map is known in advance, setting an initial capacity can improve performance.
  • Avoid frequent resizing: Adding elements frequently can cause resizing. Consider setting an appropriate initial capacity.
  • Use immutable keys: Using mutable objects as keys can lead to unpredictable behavior.

6. Performance Considerations

  • Logarithmic time performance: TreeMap provides logarithmic time performance for basic operations like put, get, and remove.
  • Memory usage: Each entry in a TreeMap requires additional memory for storing tree structure.
  • Thread safety: TreeMap is not synchronized. Use Collections.synchronizedSortedMap() if thread safety is needed.

7. Real-time Example with CRUD Operations

Managing a Student Directory:

Student.java:

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Student{name='" + name + "', age=" + age + "}";
    }
}

Main.java:

import java.util.TreeMap;

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

        // Create
        studentDirectory.put(1, new Student("Aarav", 20));
        studentDirectory.put(2, new Student("Vivaan", 22));
        studentDirectory.put(3, new Student("Diya", 21));

        // Read
        for (TreeMap.Entry<Integer, Student> entry : studentDirectory.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Student: " + entry.getValue());
        }

        // Update
        studentDirectory.put(2, new Student("Vivaan", 23));
        System.out.println("After Update:");
        for (TreeMap.Entry<Integer, Student> entry : studentDirectory.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Student: " + entry.getValue());
        }

        // Delete
        studentDirectory.remove(1);
        System.out.println("After Deletion:");
        for (TreeMap.Entry<Integer, Student> entry : studentDirectory.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Student: " + entry.getValue());
        }
    }
}

Output:

ID: 1, Student: Student{name='Aarav', age=20}
ID: 2, Student: Student{name='Vivaan', age=22}
ID: 3, Student: Student{name='Diya', age=21}
After Update:
ID: 2, Student: Student{name='Vivaan', age=23}
ID: 3, Student: Student{name='Diya', age=21}
After Deletion:
ID: 2, Student: Student{name='Vivaan', age=23}
ID: 3, Student: Student{name='Diya', age=21}

8. Conclusion

The TreeMap class in Java is a powerful class for managing key-value pairs in a sorted order. By understanding its methods, use cases, and best practices, you can effectively utilize TreeMap in your Java applications. This tutorial covers the essential methods with examples and demonstrates a real-time example with CRUD operations.

Comments