What is TreeMap?

In Java, TreeMap implements Map, NavigableMap, and AbstractMap classes. Depending on the constructor, the map gets sorted based on its natural ordering or based on a Comparator. Using a TreeMap, you can efficiently store key/value pairs sorted and provide rapid retrieval.

In contrast to a hash map, a tree map guarantees that its elements will get sorted in ascending key order.

Creating a TreeMap requires importing the java.util.TreeMap package. After importing the package, here is how to create a TreeMap in Java.

TreeMap<Key, Value> numbers = new TreeMap<>();

The code above creates a TreeMap named numbers without any parameters. In this case, TreeMap items get sorted ascendingly.

The Treemap Constructor

#1. public TreeMap()

This function constructs a new, empty tree map based on its keys' natural ordering. All keys inserted into the map must implement the Comparable interface. A key must implement a Comparable interface when inserted into the map.In addition, each of these keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any keys k1 and k2 in the map.

When a key gets inserted into the map that violates this constraint (for example, putting a string key into a map with integer keys), the put(Object key, Object value) method throws a ClassCastException.

#2. public TreeMap(Comparator<? super K> comparator)

This comparator helps construct an empty tree map. There must be a mutual comparison between all keys inserted into the map: comparator.compare(k1, k2) must not throw a ClassCastException for any keys k1 and k2 in the map.

As soon as the user attempts to insert a key that violates this constraint, the put(Object key, Object value) method throws a ClassCastException.

Parameters:

  • comparator -

the comparator will order this map. It will use the natural ordering of the keys if null.

#3. public TreeMap(Map<? extends K,? extends V> m)

This function creates a new tree map with the same mappings as the given map, ordered based on its natural order. The new map must implement a Comparable interface on all keys inserted into the new map. In addition, the keys in the map must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any keys k1 and k2 in the map. This method runs in n*log(n) time.

Parameters:

  • m - This map is to be used to place mappings

Throws:

  • ClassCastException -

If m has keys that aren't comparable, or if they aren't mutually comparable

  • NullPointerException -

A null map is specified

#4. public TreeMap(SortedMap<K,? extends V> m)

This function creates a new tree map with the same sorting and mappings as the sorted map supplied. It takes linear time to run this method.

Parameters:

  • m -

This map contains mappings that should get placed in this sorted map and a comparator that gets used for sorting.

Throws:

  • NullPointerException -

In the case of a null map

Code Sample

import java.util.*;
import java.util.concurrent.*;

public class Stud {

static TreeMap<Integer, String> tree_map;

static void create()
{

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

System.out.println("TreeMap successfully"
+ " created");
}

static void insert()
{

tree_map.put(101, "John");
tree_map.put(102, "Deep");
tree_map.put(103, "Rock");
tree_map.put(104, "Sus");

System.out.println("\nElements successfully"
+ " inserted in the TreeMap");
}

static void search(int key)
{

System.out.println("\nIs key \"" + key
+ "\" present? "
+ tree_map.containsKey(key));
}

static void search(String value)
{

System.out.println("\nIs value \"" + value
+ "\" present? "
+ tree_map.containsValue(value));
}

static void display()
{

System.out.println("\nDisplaying the TreeMap:");

System.out.println("TreeMap: " + tree_map);
}

static void traverse()
{

System.out.println("\nTraversing the TreeMap:");

for (Map.Entry<Integer, String> e :
tree_map.entrySet())
System.out.println(e.getKey() + " "
+ e.getValue());
}

public static void main(String[] args)
{

create();
insert();
search(103);
search("Deep");
display();
    traverse();
}
}

Output

TreeMap successfully created

Elements successfully inserted in the TreeMap


Is key "103" present? true


Is value "Deep" present? true

Displaying the TreeMap:

TreeMap: {101=John, 102=Deep, 103=Rock, 104=Sus}Traversing the TreeMap:

101 John

102 Deep

103 Rock

104 Sus


write your code here: Coding Playground