TreeMap in Java with Example | Java TreeMap Constructors, Methods, Sample Programs

The TreeMap class performs the Java Map Interface by using a tree. Java TreeMap Class stores the unique elements in ascending order. In this tutorial, you will learn completely about the TreeMap Class with Examples and the differences between TreeMap and HashMap class in java. Also, we will learn about the Java TreeMap class and its operations with the help of examples from this tutorial.

This Java TreeMap Tutorial Consists Of:

Java TreeMap Class

TreeMap in Java is a class that extends AbstractMap and implements the NavigableMap interface. It creates a map that is stored in a tree structure. The TreeMap provides an efficient way of storing key/values pair in sorted order and allows fast retrieval. A TreeMap guarantees that its elements will be stored in ascending key order. Some of the important points of the TreeMap are:

  1. TreeMap doesn’t have null keys but it may have multiple null values.
  2. It contains only unique elements.
  3. TreeMap guarantees that its elements will be stored in ascending key order.
  4. Java TreeMap is not synchronized.

TreeMap in Java with Example 1

Do Check:

TreeMap class Declaration

Here you can learn how to declare the package of java.util.TreeMap class:

public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable

TreeMap class Parameters

Below are the Parameters for java.util.TreeMap class:

K is the type of keys maintained by this map.
V is the type of mapped values.

Creating a TreeMap

To create a TreeMap, first, we need to import the java.util.TreeMap package. After importing the package, let’s see how we can create a TreeMap in Java.

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

where,

  • Key – a unique identifier used to associate each element (value) in a map
  • Value – elements associated by keys in a map

Here, we have created a TreeMap named numbers without any arguments. In this instance, the elements in TreeMap are sorted naturally (ascending order). Yet, we can adjust the sorting of elements by using the Comparator interface.

HashMap vs TreeMap in Java

HashMap and TreeMap both are used to key/value pairs in their object but there are some differences between HashMap and TreeMap in Javadeco which is very important for you to know which is shown below:

TreeMap in Java with Example 3

Java TreeMap Constructors

The following TreeMap constructors are defined:

  1. TreeMap(): This constructor creates an empty treemap that will be sorted according to the natural sorting order.
  2. TreeMap(Comparator comparator): It creates an empty treemap that will be sorted by using the Comparator.
  3. TreeMap(Map m): It initializes the treemap with the entries from m.
  4. TreeMap(SortedMap sm): It initializes the treemap with the entries from sm.

Methos of TreeMap in Java

1. Object put(Object key, Object value): This method is used to put key and values into a map.

2. void putAll(Map map): This method is used to copies all of the elements from the specified map to this map.

3. Object firstKey(): This method returns the first key from the sorted map.

4. Object lastKey(): This method returns the last key from the sorted map.

5. Object get(Object key): returns the value associated with the specified key.

6. int size(): returns the number of key/values pair in this map.

7. void clear(): removes all the entries from this map.

8. Object clone(): returns a shallow copy of a treemap.

9. boolean containsKey(Object key): returns true if this map contains the specified key.

9. boolean containsValue(Object value): returns true if this map contains the specified value.

10. Collection values(): This method returns a collection containing the values in the map.

11. Set keySet(): returns a set of keys in the invoking map.

12. Set entrySet(): returns a set of entries in the invoking map.

13. SortedMap headMap(key end): This method returns a sorted map for those map entries with keys
that are less than the end.

14. SortedMap tailMap(key start): This method returns a sorted map for those map entries with keys that are greater than or equal to start.

15. SortedMap subMap(key start, key end): This method returns a sorted map for those map entries with keys that are greater than or equal to start and less than the end.

Java TreeMap Example

import java.util.*;
class TreeMapExample{
public static void main(String args[]){

//creating a tree map
TreeMap<Integer, String> tmap = new TreeMap<Integer, String>();

//adding values in this map
tmap.put(101, "Rahul");
tmap.put(109, "Amit");
tmap.put(103, "Vijay");
tmap.put(102, "Suresh");
tmap.put(108, "Prashant");

//returns size of tree map
System.out.println("Tree map size is: "+tmap.size());

//check tree map contains specified key or not
System.out.println("Specified key present or not: "+tmap.containsKey(103));

////check tree map contains specified value or not
System.out.println("Specified value present or not: "+tmap.containsValue("Prashant"));

//returns tree map first key
System.out.println("Tree Map first key is: "+tmap.firstKey());

//return tree map last key
System.out.println("Treemap last key is: "+tmap.lastKey());

//returns value with specified key
System.out.println("Retrieve value associated with specified key: "+tmap.get(108));

//return key set
System.out.println("Key set is: "+tmap.keySet());

//return entry set
System.out.println("Entry Set is: "+tmap.entrySet());

//removes all the mapping
tmap.clear();
System.out.println("Removes all mapping from tree map: " +tmap);

}
}

Output:

TreeMap in Java with Example 2

Leave a Comment