TreeMap in Java: A Comprehensive Guide

TreeMap is a class in the Java Collections Framework that implements the Map interface and NavigableMap interface. It is a sorted collection, which means that the elements in the TreeMap are sorted based on their keys. TreeMap can be created by either providing a Comparator or using the natural ordering of keys. TreeMap uses a red-black tree as its underlying data structure, which provides an efficient way to store and retrieve key-value pairs.

In this article, we will explore the TreeMap class in Java and its methods with examples.

Creating a TreeMap

To create a TreeMap in Java, we can use the following constructors:

  1. TreeMap(): This constructor creates an empty TreeMap that will be sorted based on the natural ordering of keys.

  2. TreeMap(Comparator<? super K> comparator): This constructor creates an empty TreeMap that will be sorted based on the specified Comparator.

Let's see an example of creating a TreeMap using both constructors:

vbnet
// Creating an empty TreeMap TreeMap<Integer, String> treeMap1 = new TreeMap<>(); // Creating an empty TreeMap with a custom Comparator TreeMap<Integer, String> treeMap2 = new TreeMap<>(Comparator.reverseOrder());

Inserting and Retrieving Elements

To insert an element into a TreeMap, we can use the put() method. It takes two parameters - the key and the value. If the key already exists in the TreeMap, its value will be updated with the new value.

javascript
// Inserting elements into a TreeMap treeMap1.put(1, "One"); treeMap1.put(2, "Two"); treeMap1.put(3, "Three");

To retrieve an element from a TreeMap, we can use the get() method. It takes one parameter - the key whose associated value is to be retrieved.

javascript
// Retrieving elements from a TreeMap String value1 = treeMap1.get(1); // returns "One" String value2 = treeMap1.get(4); // returns null

Removing Elements

To remove an element from a TreeMap, we can use the remove() method. It takes one parameter - the key of the element to be removed.

csharp
// Removing an element from a TreeMap treeMap1.remove(1); // removes the key-value pair with key 1

Traversing a TreeMap

There are several ways to traverse a TreeMap. One of the common ways is to use a for-each loop over the entrySet() of the TreeMap. The entrySet() method returns a set of key-value pairs contained in the TreeMap.

vbnet
// Traversing a TreeMap using for-each loop for (Map.Entry<Integer, String> entry : treeMap1.entrySet()) { Integer key = entry.getKey(); String value = entry.getValue(); System.out.println(key + " -> " + value); }

The output of the above code would be:

rust
2 -> Two 3 -> Three

Navigating a TreeMap

TreeMap provides several methods to navigate through the elements in the collection based on the keys. Some of these methods are:

  1. higherKey(K key): Returns the least key strictly greater than the given key, or null if there is no such key.

  2. lowerKey(K key): Returns the greatest key strictly less than the given key, or null if there is no such key.

  3. floorKey(K key): Returns the greatest key less than or equal to the given key, or null if there is no such key.

  4. ceilingKey(K key): Returns the least key greater than or equal to the given key, or null if there is no such key.

Let's see an example of how these methods work:

java
import java.util.TreeMap; public class TreeMapExample { public static void main(String[] args) { TreeMap<Integer, String> treeMap = new TreeMap<>(); treeMap.put(1, "one"); treeMap.put(3, "three"); treeMap.put(5, "five"); treeMap.put(7, "seven"); treeMap.put(9, "nine"); System.out.println("Navigating TreeMap:"); System.out.println("TreeMap: " + treeMap); Integer key = 4; System.out.println("Finding element greater than key " + key); System.out.println("Result: " + treeMap.higherKey(key)); key = 5; System.out.println("Finding element less than key " + key); System.out.println("Result: " + treeMap.lowerKey(key)); key = 6; System.out.println("Finding element less than or equal to key " + key); System.out.println("Result: " + treeMap.floorKey(key)); key = 3; System.out.println("Finding element greater than or equal to key " + key); System.out.println("Result: " + treeMap.ceilingKey(key)); } }

Output:

vbnet
Navigating TreeMap: TreeMap: {1=one, 3=three, 5=five, 7=seven, 9=nine} Finding element greater than key 4 Result: 5 Finding element less than key 5 Result: 3 Finding element less than or equal to key 6 Result: 5 Finding element greater than or equal to key 3 Result: 3

In this example, we first create a TreeMap and add some key-value pairs to it. Then we use the methods higherKey, lowerKey, floorKey, and ceilingKey to navigate through the TreeMap.

In the first example, we use higherKey to find the least key strictly greater than 4, which is 5. In the second example, we use lowerKey to find the greatest key strictly less than 5, which is 3. In the third example, we use floorKey to find the greatest key less than or equal to 6, which is 5. Finally, in the fourth example, we use ceilingKey to find the least key greater than or equal to 3, which is 3.

Using these methods can be useful when you need to find elements that are close to a specific key in a TreeMap.

Previous Post Next Post