Java Treemap

The Java TreeMap class is implemented using a red-black tree structure, which offers an effective way to store pairs of keys and values in a sorted manner.

Within the java.util package, you can find the Java TreeMap class, an integral part of the Java Collections Framework. This class is an extension of the AbstractMap class and incorporates the NavigableMap interface. TreeMap is a reliable red-black tree implementation designed for organizing key-value pairs. It is particularly useful when maintaining key-value pairs in a specific order is essential, as it retains an ascending sequence. Furthermore, TreeMap ensures uniqueness by only containing distinct elements, ensuring each key is associated with a unique value. Despite not allowing null keys, TreeMap can accommodate multiple null values.

The important points about Java TreeMap class are:

  • Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • Java TreeMap contains only unique elements.
  • Java TreeMap cannot have a null key but can have multiple null values.
  • Java TreeMap is non synchronized.
  • Java TreeMap maintains ascending order.
  • TreeMap Class Declaration

Let's examine the declaration of the java.util.TreeMap class.

Example

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

TreeMap Class Parameters

Exploring the Specifications of the java.util.TreeMap class:

-

  • : Represents the category of keys that are managed by this map.

-

  • : Denotes the kind of values that are mapped.
  • Constructors of Java TreeMap class

Constructor Description
TreeMap() It is used to construct an empty tree map that will be sorted using the natural order of its key.
TreeMap(Comparator<? super K> comparator) It is used to construct an empty tree-based map that will be sorted using the comparator comp.
TreeMap(Map<? extends K,? extends V> m) It is used to initialize a TreeMap with the entries from m, which will be sorted using the natural order of the keys.
TreeMap(SortedMap<K,? extends V> m) It is used to initialize a TreeMap with the entries from the SortedMap sm, which will be sorted in the same order as sm.
TreeMap(Collection<? extends K> c) It constructs a tree map containing the elements of the specified collection, sorted using their natural order.
TreeMap(SortedMap<K,? extends V> m m, ComparatorComparator<K> comparator) It initializes a TreeMap with the entries from the provided sorted map and uses the given comparator for sorting.

Methods of Java TreeMap Class

Method Description
Map.Entry<K,V> ceilingEntry(K key) It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key.
K ceilingKey(K key) It returns the least key, greater than the specified key or null if there is no such key.
void clear() It removes all the key-value pairs from a map.
Object clone() It returns a shallow copy of TreeMap instance.
Comparator<? super K> comparator() It returns the comparator that arranges the key in order, or null if the map uses the natural ordering.
NavigableSet<K> descendingKeySet() It returns a reverse order NavigableSet view of the keys contained in the map.
NavigableMap<K,V> descendingMap() It returns the specified key-value pairs in descending order.
Map.EntryfirstEntry() It returns the key-value pair having the least key.
Map.Entry<K,V> floorEntry(K key) It returns the greatest key, less than or equal to the specified key, or null if there is no such key.
void forEach(BiConsumer<? super K,? super V> action) It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
SortedMap<K,V> headMap(K toKey) It returns the key-value pairs whose keys are strictly less than toKey.
NavigableMap<K,V> headMap(K toKey, boolean inclusive) It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey.
Map.Entry<K,V> higherEntry(K key) It returns the least key strictly greater than the given key, or null if there is no such key.
K higherKey(K key) It is used to return true if this map contains a mapping for the specified key.
SetkeySet() It returns the collection of keys exist in the map.
Map.Entry<K,V> lastEntry() It returns the key-value pair having the greatest key, or null if there is no such key.
Map.Entry<K,V> lowerEntry(K key) It returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
K lowerKey(K key) It returns the greatest key strictly less than the given key, or null if there is no such key.
NavigableSet<K> navigableKeySet() It returns a NavigableSet view of the keys contained in this map.
Map.Entry<K,V> pollFirstEntry() It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
Map.Entry<K,V> pollLastEntry() It removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
V put(K key, V value) It inserts the specified value with the specified key in the map.
void putAll(Map<? extends K,? extends V> map) It is used to copy all the key-value pair from one map to another map.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction<? super K,? super V,? extends V> function) It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) It returns key-value pairs whose keys range from fromKey to toKey.
SortedMap<K,V> subMap(K fromKey, K toKey) It returns key-value pairs whose keys range from fromKey, inclusive, to toKey, exclusive.
SortedMap<K,V> tailMap(K fromKey) It returns key-value pairs whose keys are greater than or equal to fromKey.
NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) It returns key-value pairs whose keys are greater than (or equal to, if inclusive is true) fromKey.
boolean containsKey(Object key) It returns true if the map contains a mapping for the specified key.
boolean containsValue(Object value) It returns true if the map maps one or more keys to the specified value.
K firstKey() It is used to return the first (lowest) key currently in this sorted map.
V get(Object key) It is used to return the value to which the map maps the specified key.
K lastKey() It is used to return the last (highest) key currently in the sorted map.
V remove(Object key) It removes the key-value pair of the specified key from the map.
Set<Map.Entry<K,V>> entrySet() It returns a set view of the mappings contained in the map.
int size() It returns the number of key-value pairs exists in the hashtable.
Collectionvalues() It returns a collection view of the values contained in the map.

Java TreeMap Example

File Name: TreeMap1.java

Example

import java.util.*;

class TreeMap1{

 public static void main(String args[]){

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

	  map.put(100,"Amit");  

	  map.put(102,"Ravi");  

	  map.put(101,"Vijay");  

	  map.put(103,"Rahul");  

	  

	  for(Map.Entry m:map.entrySet()){  

	   System.out.println(m.getKey()+" "+m.getValue());  

	  }  

 }

}

Output:

Output

100 Amit

101 Vijay

102 Ravi

103 Rahul

Explanation

The following Java example demonstrates the process of storing key-value pairs and iterating through the elements of a TreeMap structure. At the beginning, the code imports the java.util.* package to access the TreeMap class and its related functionalities. Subsequently, an instance of TreeMap named map is created with integer keys and string values. Through the utilization of the put function, four pairs of keys and values are inserted into the TreeMap. Each entry consists of a string value associated with an integer key.

The entrySet function produces a set that contains all the mappings from the map. This set is then iterated through using a for-each loop to access each entry in the TreeMap. Within the loop, the getKey and getValue functions of the Map.Entry interface are employed to retrieve each entry, and its corresponding key-value pair is displayed on the console.

Java TreeMap Example: remove

File Name: TreeMap2.java

Example

import java.util.*;

public class TreeMap2 {

   public static void main(String args[]) {

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

	  map.put(100,"Amit");  

	  map.put(102,"Ravi");  

	  map.put(101,"Vijay");  

	  map.put(103,"Rahul");  

	  System.out.println("Before invoking remove() method");

	  for(Map.Entry m:map.entrySet())

	  {

		  System.out.println(m.getKey()+" "+m.getValue());	  

	  }

	  map.remove(102);	  

	  System.out.println("After invoking remove() method");

	  for(Map.Entry m:map.entrySet())

	  {

		  System.out.println(m.getKey()+" "+m.getValue());	  

	  }

	  }

}

Output:

Output

Before invoking remove() method

100 Amit

101 Vijay

102 Ravi

103 Rahul

After invoking remove() method

100 Amit

101 Vijay

103 Rahul

Explanation

The Java code snippet demonstrates the process of deleting an entry by utilizing the remove function and managing key-value pairs through the utilization of the TreeMap class. Initially, the TreeMap is populated with key-value pairs associating integer keys with corresponding string values.

Next, a TreeMap is showcased by adding, removing, and iterating over entries with a key of 102 using the remove method. This code snippet exemplifies the TreeMap's ability to maintain order and be modified.

Java TreeMap Example: NavigableMap

File Name: TreeMap3.java

Example

import java.util.*;

class TreeMap3{

 public static void main(String args[]){

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

	  map.put(100,"Amit");  

	  map.put(102,"Ravi");  

	  map.put(101,"Vijay");  

	  map.put(103,"Rahul");  

	  //Maintains descending order

	  System.out.println("descendingMap: "+map.descendingMap());

	  //Returns key-value pairs whose keys are less than or equal to the specified key.

	  System.out.println("headMap: "+map.headMap(102,true));

	  //Returns key-value pairs whose keys are greater than or equal to the specified key.

	  System.out.println("tailMap: "+map.tailMap(102,true));

	  //Returns key-value pairs exists in between the specified key.

	  System.out.println("subMap: "+map.subMap(100, false, 102, true)); 

 }

}

Output:

Output

descendingMap: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}

headMap: {100=Amit, 101=Vijay, 102=Ravi}

tailMap: {102=Ravi, 103=Rahul}

subMap: {101=Vijay, 102=Ravi}

Explanation

The following Java code demonstrates the construction of a map that organizes key-value pairs in an ascending order based on the keys. This is achieved by utilizing the TreeMap class in conjunction with the NavigableMap interface. After populating the TreeMap with integer keys and their corresponding string values, the code showcases various navigation methods provided by the NavigableMap interface.

Apart from showcasing functions such as headMap, tailMap, and subMap for fetching segments of the map according to defined key ranges, TreeMap also offers the descending map, which alters the sequence of key-value pairs. These functionalities illustrate the versatility and capabilities TreeMap offers for organizing and fetching key-value pairs based on different criteria.

Java TreeMap Example: SortedMap

Example

import java.util.*;

class TreeMap4{

 public static void main(String args[]){

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

	  map.put(100,"Amit");  

	  map.put(102,"Ravi");  

	  map.put(101,"Vijay");  

	  map.put(103,"Rahul");  

	  //Returns key-value pairs whose keys are less than the specified key.

	  System.out.println("headMap: "+map.headMap(102));

	  //Returns key-value pairs whose keys are greater than or equal to the specified key.

	  System.out.println("tailMap: "+map.tailMap(102));

	  //Returns key-value pairs exists in between the specified key.

	  System.out.println("subMap: "+map.subMap(100, 102));  

 }

}

Output:

Output

headMap: {100=Amit, 101=Vijay}

tailMap: {102=Ravi, 103=Rahul}

subMap: {100=Amit, 101=Vijay}

Explanation

In this Java program, the utilization of the TreeMap class and the SortedMap interface is demonstrated to create a sorted map where key-value pairs are sorted based on the natural ordering of keys, which are integers in this scenario. By initializing the TreeMap with integer keys and corresponding string values, the code leverages methods provided by the SortedMap interface to retrieve subsets of the map using defined key ranges.

Emphasis is placed on the functionalities of headMap, tailMap, and subMap, which provide key-value pairs with keys that are less than, greater than, or equal to, and within the specified key range. These operations showcase TreeMap's ability to efficiently manage and fetch key-value pairs based on their sorted order.

What is difference between HashMap and TreeMap?

HashMap TreeMap
HashMap does not guarantee a sorted order of elements. TreeMap guarantees a sorted order of elements based on the natural ordering of keys or a custom comparator.
HashMap is generally faster for insertion and retrieval operations, especially for large datasets. TreeMap offers efficient range queries and operations like finding the closest key.
HashMap uses hashing for storing key-value pairs, providing constant-time performance for basic operations (e.g., get, put, remove) on average. TreeMap uses a red-black tree internally, resulting in logarithmic-time complexity for most operations, making it slightly slower than HashMap for basic operations.
Iterating over elements in a HashMap does not guarantee any specific order. Iterating over elements in a TreeMap results in sorted order based on the keys.
HashMap allows null values, and multiple null values can be associated with different keys. TreeMap allows null values but not null keys.
HashMap is not synchronized, making it not thread-safe. TreeMap is not synchronized, making it not thread-safe.
HashMap is part of the java.util package. TreeMap is part of the java.util package and implements the NavigableMap interface.

Java TreeMap Example: Book

File Name: MapExample.java

Example

import java.util.*;  

class Book {  

int id;  

String name,author,publisher;  

int quantity;  

public Book(int id, String name, String author, String publisher, int quantity) {  

    this.id = id;  

    this.name = name;  

    this.author = author;  

    this.publisher = publisher;  

    this.quantity = quantity;  

}  

}  

public class MapExample {  

public static void main(String[] args) {  

    //Creating map of Books  

    Map<Integer,Book> map=new TreeMap<Integer,Book>();  

    //Creating Books  

    Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);  

    Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);  

    Book b3=new Book(103,"Operating System","Galvin","Wiley",6);  

    //Adding Books to map 

    map.put(2,b2);

    map.put(1,b1);

    map.put(3,b3);

    

    //Traversing map

    for(Map.Entry<Integer, Book> entry:map.entrySet()){  

    	int key=entry.getKey();

    	Book b=entry.getValue();

        System.out.println(key+" Details:");

        System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); 

    }  

}  

}

Output:

Output

1 Details:

101 Let us C Yashwant Kanetkar BPB 8

2 Details:

102 Data Communications & Networking Forouzan Mc Graw Hill 4

3 Details:

103 Operating System Galvin Wiley 6

Explanation

This Java example demonstrates the process of saving and fetching instances of a personalized class named Book through a TreeMap. At the outset, the Book class is created with a constructor responsible for setting the values of properties like id, title, writer, press, and quantity.

In the MapExample class's main method, a TreeMap named "map" is created to store integer keys and Book objects as corresponding values. Three Book objects are instantiated with unique ids and inserted into the TreeMap using the ids as keys. Subsequently, a for-each loop is utilized to iterate through the TreeMap elements, retrieving each key-value pair, which consists of a key and its associated Book object, from the map.

Input Required

This code uses input(). Please provide values below: