TreeMap in Java | Usage with Coding Examples

TreeMap in Java | Usage with Coding Examples

In Java, TreeMap is a class that implements the Map interface and provides a red-black tree-based implementation of a map.

It stores data into key-value pairs in a sorted order that is based on the keys. This means that TreeMap maintains the order of the elements according to the natural order of their keys.

Let’s understand the working example of creating a TreeMap in Java.

How to Create TreeMap in Java

import java.util.TreeMap;
public class MainClass {
    public static void main(String[] args) {
        // Creating a TreeMap
        TreeMap<String, Integer> treeMap = new TreeMap<>();
        // Adding elements to the TreeMap
        treeMap.put("Rohan", 30);
        treeMap.put("Sohan", 25);
        treeMap.put("Mohan", 40);
        treeMap.put("John", 35);
        treeMap.put("Sorabh", 20);

        // Displaying the TreeMap
        System.out.println("TreeMap: " + treeMap);
    }
}

Output:

TreeMap: {John=35, Mohan=40, Rohan=30, Sohan=25, Sorabh=20}

In the above example, we create a TreeMap and add some key-value pairs to it. We then display the TreeMap to the console.

TreeMap sorts elements on the natural order of the keys, which is lexicographic order in the above example case.

Let’s understand creating TreeMap in other ways:

Creating TreeMap using Comparator

In this example, we create a TreeMap with a custom key order by passing a Comparator object that sorts the keys in reverse order to the TreeMap constructor. 

We then add some key-value pairs to the TreeMap and display the sorted TreeMap.

import java.util.Comparator;
import java.util.TreeMap;

class MainClass {
	public static void main(String[] args) {

		// Creating a TreeMap
        TreeMap<String, Integer> treeMap = new TreeMap<>(Comparator.reverseOrder());
		// Adding elements to the TreeMap
		treeMap.put("Rohan", 30);
		treeMap.put("Sohan", 25);
		treeMap.put("Mohan", 40);
		treeMap.put("John", 35);
		treeMap.put("Sorabh", 20);

		// Displaying the TreeMap
        System.out.println("TreeMap with custom key order: " + treeMap);
	}
}

Output:

TreeMap with custom key order: {Sorabh=20, Sohan=25, Rohan=30, Mohan=40, John=35}

Java TreeMap class Methods

Here are some of the commonly used methods of the Java TreeMap class:

put(key, value)

It adds the specified key-value pair to the TreeMap. If the key already exists in the TreeMap, the new value replaces the existing one. It returns the previous value associated with the key, or null if there was no mapping for the key.

get(key)

It returns the value associated with the specified key in the TreeMap, or null if the key is not present in the TreeMap.

remove(key)

It removes the key-value pair associated with the specified key from the TreeMap. Returns the value that was associated with the key, or null if the key is not present in the TreeMap.

size()

It returns the number of key-value pairs in the TreeMap.

clear()

It removes all key-value pairs from the TreeMap.

containsKey(key)

It returns true if the TreeMap contains a key-value pair with the specified key, otherwise false.

containsValue(value)

It returns true if the TreeMap contains a key-value pair with the specified value, otherwise false.

firstKey()

It returns the first (lowest) key in the TreeMap, or null if the TreeMap is empty.

lastKey()

It returns the last (highest) key in the TreeMap, or null if the TreeMap is empty.

keySet()

It returns a Set view of the keys contained in the TreeMap.

values()

It returns a Collection view of the values contained in the TreeMap.

entrySet()

It returns a Set view of the key-value pairs contained in the TreeMap.

Adding, Removing, and Finding TreeMap Elements

Here, we used put(), remove(), and firstKey() methods to find add, remove and get elements respectively.

import java.util.TreeMap;

class MainClass {
	public static void main(String[] args) {

		// Creating a TreeMap
		TreeMap<String, Integer> treeMap = new TreeMap<>();
		// Adding elements to the TreeMap
		treeMap.put("Rohan", 30);
		treeMap.put("Sohan", 25);
		treeMap.put("Mohan", 40);
		treeMap.put("John", 35);
		treeMap.put("Sorabh", 20);

		// Displaying the TreeMap
		System.out.println("TreeMap: " + treeMap);
		
		// Removing elements
		treeMap.remove("Mohan");
		
		// Displaying the TreeMap
		System.out.println("TreeMap: " + treeMap);
		
		// accessing the first key
		String val = treeMap.firstKey();
		System.out.println(val);
	}
}

Output:

TreeMap: {John=35, Mohan=40, Rohan=30, Sohan=25, Sorabh=20}
TreeMap: {John=35, Rohan=30, Sohan=25, Sorabh=20}
John

Frequency Counter using TreeMap

Let’s take another example of TreeMap to count the frequency of characters in the string.

import java.util.TreeMap;

class MainClass {
	public static void main(String[] args) {

		// Creating a TreeMap
		TreeMap<Character, Integer> frequencyMap = new TreeMap<>();

		// Counting the frequency of characters in a string
		String str = "hello world dlrow";
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (frequencyMap.containsKey(c)) {
				frequencyMap.put(c, frequencyMap.get(c) + 1);
			} else {
				frequencyMap.put(c, 1);
			}
		}

		// Displaying the frequency map
		System.out.println("Frequency map: " + frequencyMap);
	}
}

Output:

Frequency map: { =1, d=1, e=1, h=1, l=3, o=2, r=1, w=1}

In this example, we use a TreeMap to count the frequency of characters in a string. 

We create a TreeMap with Character keys and Integer values to store the frequency count of each character in the input string. 

We then iterate over each character in the string, update the frequency count in the TreeMap, and finally display the frequency map.

Advantages of using TreeMap in Java

Here are some advantages of using TreeMap in Java:

  1. Ordered keys:

TreeMap is implemented using a self-balancing binary search tree, which keeps the keys in sorted order. This allows for efficient range queries, such as finding all keys between two given values.

  1. Fast lookup:

Since the keys are stored in a binary search tree, lookups are efficient and can be performed in O(log n) time, where n is the number of keys in the map. This makes TreeMap a good choice for large datasets where lookup performance is important.

  1. Custom sorting:

TreeMap allows you to specify a custom Comparator to define the sorting order of the keys. This can be useful when you need to sort keys in a non-default order, such as sorting strings in reverse alphabetical order.

  1. Key and value associations:

TreeMap provides a way to associate a value with each key, allowing you to store and retrieve both keys and their associated values.

  1. Memory efficiency:

TreeMap is implemented using a balanced binary search tree, which uses memory efficiently. The tree is balanced to ensure that the height of the tree is always logarithmic, which means that the memory used by the tree is proportional to the number of keys stored in the map.

  1. Thread safety:

TreeMap is not thread-safe by default, but it can be made thread-safe by using appropriate synchronization techniques.

When to use TreeMap in Java?

TreeMap is a powerful data structure in Java that allows efficient storage and retrieval of key-value pairs. It provides fast lookups, ordered keys, custom sorting, and memory efficiency.

It is useful for a variety of applications where key-value storage and retrieval are required, including sorting, searching, and indexing.

Leave a Reply

Your email address will not be published. Required fields are marked *