Unlocking the Power of TreeMap Class in Java: Efficient, Sorted, and Versatile Data Management

What is TreeMap Class in Java?

  • The TreeMap class in Java is a part of the java.util package and actualizes the NavigableMap interface, which may be a subtype of the SortedMap interface.
  • It gives a map implementation where the keys are stored in a sorted order.
  • This class is based on a Red-Black tree structure, a self-balancing binary search tree, which ensures that operations like insertion, deletion, and search are performed in O(log n) time.
  • A key highlight of TreeMap is that it keeps up the order of its keys.
  • By default, the keys are sorted in their natural order (i.e., concurring to the compareTo() method of the key class).
  • In any case, the sorting can moreover be customized by giving a Comparator when building the TreeMap.
TreeMap in Java
TreeMap in Java

Key Characteristics of TreeMap Class in Java:

  1. Sorted Order: The keys in a TreeMap are sorted based on their natural ordering or by a comparator provided during initialization.
  2. Unique Keys: A TreeMap does not permit duplicate keys. In case a new key is inserted that’s as of now display, the old value is replaced with the new one.
  3. NavigableMap Interface: Being a NavigableMap, TreeMap gives methods to explore through the map, such as higherKey(), lowerKey(), ceilingKey(), and floorKey().
  4. Efficient Search Operations: Due to its Red-Black tree structure, it offers viable operations for search, insertion, and removal with a time complexity of O(log n).
  5. Null Keys and Values: A TreeMap does not allow null keys (throws NullPointerException), but it permits null values.

 

Common Methods in TreeMap Class in Java:

  1. put(K key, V value):  Adds a key-value pair to the map. On the off chance that the key as of presently exists, its value is updated.
  2. get(Object key):  Retrieves the value related with the given key.
  3. remove(Object key):  Removes the key-value pair for the required key.
  4. containsKey(Object key): Checks if the map contains the required key.
  5. firstKey(): Returns the first (lowest) key within the map.
  6. lastKey(): Returns the last (highest) key within the map.
  7. size(): Returns the number of key-value pairs within the map.
  8. clear(): Removes all key-value pairs from the map.

Example 1: Basic TreeMap Usage

Let’s see at a direct example where we make a TreeMap,insert a few key-value pairs, and perform fundamental operations:

import java.util.*;

public class TreeMapExample {

public static void main(String[] args)

TreeMap<String,Integer> map=new TreeMap<>();

// Adding key-value pairs

map.put(“Apple”, 3);

map.put(“Banana”, 2);

map.put(“Cherry”, 5);

// Displaying the TreeMap

System.out.println(“TreeMap: ” + map);

// Getting a value associated with a key

System.out.println(“Value for ‘Apple’: ” + map.get(“Apple”));

// Removing a key-value pair

map.remove(“Banana”);

System.out.println(“After removing ‘Banana’: ” + map);

// Checking if a key exists

System.out.println(“Contains ‘Cherry’? ” + map.containsKey(“Cherry”));

// Getting the first and last keys

System.out.println(“First key: ” + map.firstKey());

System.out.println(“Last key: ” + map.lastKey());

// Size of the TreeMap

System.out.println(“Size of TreeMap: ” + map.size());

}

}

Output:

TreeMap: {Apple=3, Banana=2, Cherry=5}

Value for 'Apple': 3

After removing 'Banana': {Apple=3, Cherry=5}

Contains 'Cherry'? true

First key: Apple

Last key: Cherry

Size of TreeMap: 2

In the above example:

  • We insert three key-value pairs into the TreeMap.
  • We retrieve the value for the key “Apple”.
  • We remove the entry with the key “Banana”.
  • We check whether the map contains a particular key (“Cherry”).
  • We retrieve the first and last keys within the map.
  • At last, we print the size of the map.

 

Example 2: TreeMap with Custom Sorting

You’ll as well customize the arrange of the keys by using a comparator.For example,if you’d like to sort the keys in reverse order,you’ll pass a comparator to the TreeMap constructor.

import java.util.*;

public class TreeMapCustomSortExample {

public static void main(String[] args) {

// Custom comparator to sort keys in reverse order

TreeMap<String, Integer> map = new TreeMap<>(Collections.reverseOrder());

// Adding key-value pairs

map.put(“Apple”, 3);

map.put(“Banana”, 2);

map.put(“Cherry”, 5);

// Displaying the TreeMap with custom sorting

System.out.println(“TreeMap with Reverse Order: ” + map);

}

}

Output:

TreeMap with Reverse Order: {Cherry=5, Banana=2, Apple=3}

Here,the keys are sorted in reverse alphabetical order since of the reverseOrder() comparator.

Leave a Comment