Treemap in Java

Besides the AbstractMap Class, Java's TreeMap is utilized to implement the NavigableMap and Map interface. Depending on the function Object() used, the map is ordered either by the Comparator available at map formation or by the logical ordering of its keys. In this article, we will discuss Java treemap, its features, and various key points to remember while working with treemap. We will also discuss the construction process of a treemap along with constructors, methods, and multiple examples related to treemap.

What is Java Treemap

The Java TreeMap class implements red-black trees. It offers a practical way to keep the key-values organized. It can also be defined as an implementation of NavigableMap based on Red-Black trees. It is arranged in the order that its keys naturally appear.

Similar to the HashMap class, the TreeMap class implements the Map interface. The primary distinction between both is that TreeMap is sorted in ascending order of its keys whereas HashMap is an unsorted collection.

java treemap

The key-value pairs can be sorted and stored effectively using this method. Similar to any other sorting map, the treemap's storage order has to be constant with equals regardless of the specified comparators. The implementation of a treemap isn’t accompanied in the sense that a map must be externally synchronized if it is used by many threads simultaneously and one of the threads changes the map fundamentally.

                                   Wish to make a career in the world of Java? Start with HKR'S Java Training

Key points of Java Treemap

The following are the Java TreeMap class key points to remember:

Based on the key, Java TreeMap contains values. It extends the AbstractMap class and implements the NavigableMap interface.

Java TreeMap only has distinct elements.

  • Java TreeMap can have many null values but not a null key.
  • TreeMap in Java is not synchronized.
  • Ascending order is maintained via Java TreeMap.
Creating a Treemap

We must first import the java.util.TreeMap package in order to create a TreeMap. Here is how to make a Java TreeMap after importing the library.

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

Here,
key: is a special identification number used to link each value (element) in a map.
Value: elements on a map that are linked by keys

Without using any arguments, we generated a TreeMap using the name numbers in the code above. In this instance, TreeMap's elements are organically sorted (ascending order).

However, by utilizing the Comparator interface, we may adjust how the components are sorted. It will be covered in more detail later in this course.

Constructors in Treemap

We must first build a TreeMap class’s object in order to generate a TreeMap. The class of TreeMap has a number of constructors that can be used to create a TreeMap. The constructors accessible in the class are listed below. Following are constructors in a treemap:

1.Treemap():

By leveraging the keys' natural order, this function Object() creates an empty treemap to be sorted.

Let us see the Java example below to understand the working of this treemap() constructor.

import java.util.*;
import java.util.concurrent.*;
public class HKR {

static void XConstructor()
{
TreeMap<Integer, String> tree_map
= new TreeMap<Integer, String>();

tree_map.put(10, "Hello!");
tree_map.put(15, "How");
tree_map.put(20, "Are");
tree_map.put(25, "You");
tree_map.put(30, "Dear");

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

public static void main(String[] args)
{
System.out.println("TreeMap by using the "
+ "TreeMap() constructor is:\n");

XConstructor();
}
}

The Output of this Java code will be:

TreeMap by using the TreeMap() constructor is:
The TreeMap is: {10=Hello!, 15=How, 20=Are, 25=You, 30=Dear}
2.TreeMap (comparator comp)

This function Object() is used for creating a TreeMap object which is empty and whose members require external sorting order specification.

Let us see the Java example below to understand the working of this Treemap(comparator comp) constructor.

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

class Stud1 {

int rollno;
String name, address;

public Stud1(int rollno, String name, String address)
{

this.rollno = rollno;
this.name = name;
this.address = address;
}

public String toString()
{
return this.rollno + " " + this.name + " "
+ this.address;
}
}


class Sortbyroll implements Comparator {


public int compare(Stud1 a, Stud1 b)
{
return a.rollno - b.rollno;
}
}

public class HKR {

static void Example2ndConstructor()
{
TreeMap<Stud1, Integer> tree_map
= new TreeMap<Stud1, Integer>(
new Sortbyroll());

tree_map.put(new Stud1(111, "x", "Arabic"), 2);
tree_map.put(new Stud1(131, "y", "Banana"), 3);
tree_map.put(new Stud1(121, "z", "Costa"), 1);

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

public static void main(String[] args)
{

System.out.println("TreeMap using "
+ "TreeMap(Comparator)"
+ " constructor will be:\n");
Example2ndConstructor();
}
}

The Output of this Java code will be:

TreeMap using TreeMap(Comparator) constructor will be:
TreeMap: {111 y Banana=2, 121 z Costa=1, 131 x Arabic=3}
3.TreeMap (Map m)

When calling this function, the elements from the supplied map X will be ordered according to the key's natural order to initialize a TreeMap.

Let us see the Java example below to understand the working of this constructor.

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

public class TreeMapImplementation {

static void ExampleConstructor()
{
Map<Integer, String> hash_map
= new HashMap<Integer, String>();

hash_map.put(10, "Hello!");
hash_map.put(15, "How");
hash_map.put(20, "are");
hash_map.put(25, "you");
hash_map.put(30, "Dear");

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

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

public static void main(String[] args)
{

System.out.println("TreeMap using "
+ "TreeMap(Map)"
+ " constructor is:\n");

ExampleConstructor();
}
}

The Output of this Java code will be:

TreeMap using TreeMap(Map) constructor is:
TreeMap: {10=Hello!, 15=How, 20=are, 25=you, 30=Dear
4.TreeMap (SortedMap sm)

The items from the specified sorted map will also be stored in a similar arrangement as the specified sorted map when using this function Object() to initialize a TreeMap.

Let us see the Java example below to understand the working of this constructor.

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

public class HKR {

static void ExampleConstructor()
{
SortedMap<Integer, String> sorted_map
= new ConcurrentSkipListMap<Integer, String>();

sorted_map.put(10, "Hello!");
sorted_map.put(15, "How");
sorted_map.put(20, "are");
sorted_map.put(25, "you");
sorted_map.put(30, "Dear");

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

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

public static void main(String[] args)
{
System.out.println("TreeMap using "
+ "TreeMap(SortedMap)"
+ " constructor:\n");

ExampleConstructor();
}
}


The Output of this Java code will be:


TreeMap using TreeMap(SortedMap) constructor:
TreeMap: {10=Hello!, 15=How, 20=are, 25=you, 30=Dear}

Java Certification Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning
Methods in Treemap

Here are a lot of methods for Java Treemap. Let us have a look at them below:

  • clear(): The method clears the map and removes any mappings from the TreeMap.
  • clone(): This TreeMap's shallow copy is what this method returns.
  • containsValue(Object value): If this map maps one or more keys to the given value, it will return true. 
  • containsKey(Object key):  This method will return true as there is mapping for a given key in this map.
  • entryset(): a mapping view set in this map is returned.
  • firstkey(): Returns the lowest first key found in the sorted map at the moment.
  • getObjectkey(): Returns value that this map converts the given key to
  • headMap(Object key_value): The method returns a view of the portion of the map which is exclusively below the value indicated by the key value.
  • Keyset(): A Set view of the keys in the treemap is the result of the procedure.
  • lastkey(): returns the highest key in this sorted map at the moment.
  • putAll(Map map): copies every mapping from the target map to the one you provide.
  • Size(): gives the amount of key-value mapped values in this map.

Let us now see a Treemap example below:

import java.util.*; 
class TreeMap1{
public static void main(String args[]){
TreeMap<Integer,String> map=new TreeMap<Integer,String>();
map.put(1,"Apple");
map.put(2,"Banana");
map.put(3,"Cherry");
map.put(4,"Dolce");

for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

The output of this program will be:


1 Apple 2 Banana 3 Cherry 4 Dolce

                                                                Top 30 frequently asked JAVA Interview Questions !

Subscribe to our youtube channel to get new updates..!

Performing Various Operations on TreeMap
1.Adding elements

We can employ the put() method to include a new element in the TreeMap. The TreeMap, however, does not maintain the order of insertion. The keys will be evaluated and sorted. It will be done in increasing order internally for each element.

Let us understand this better with the help of an example:

import java.util.*;

class HKR {

public static void main(String args[])
{
TreeMap tm1 = new TreeMap();
tm1.put(3, "HKR");
tm1.put(2, "Trainings");
tm1.put(1, "for learners");

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

tm2.put(new Integer(3), "HKR");
tm2.put(new Integer(2), "Trainings");
tm2.put(new Integer(1), "for learners");
System.out.println(tm1);
System.out.println(tm2);
}
}

The output of this program will be:

{1=for learners, 2=Trainings, 3=HKR}
{1=for learners, 2=Trainings, 3=HKR}
2.Changing Elements

In case we want to update an element after adding it, we can do so by adding it once more using the put() method. The values of the keys can be modified by simply inputting the updated value of the key that needs to be changed because the items in the treemap are indexed that use the keys.

Let us understand this better with the help of an example:

import java.util.*;
class HKR {

public static void main(String args[])
{
TreeMap<Integer, String> tm
= new TreeMap<Integer, String>();

tm.put(3, "Welcome");
tm.put(2, "to");
tm.put(1, "HKR");

System.out.println(tm);

tm.put(2, "to");
System.out.println(tm);
}
}

The output of this program will be:


{1=HKR, 2=to, 3=Welcome}
{1=HKR, 2=to, 3=Welcome}
3.Removing Element:

The remove() method can be used to delete an item from the TreeMap. If there is a mapping for the key in the treemap, it is removed by this method using the key value.

Let us understand this better with the help of an example:

import java.util.*;
class HKR {

public static void main(String args[])
{
TreeMap<Integer, String> tm
= new TreeMap<Integer, String>();

tm.put(3, "Welcome");
tm.put(2, "to");
tm.put(1, "HKR");
tm.put(4, "Learners");

System.out.println(tm);

tm.remove(4);
System.out.println(tm);
}
}

The output of this program will be:


{1=HKR, 2=to, 3=Welcome, 4=Learners}
{1=HKR, 2=to, 3=Welcome}
4.Iterating through keymap:

The Map can be iterated through in a variety of ways. The most well-known method is to obtain the keys using a for-each loop. The getValue() method is used to determine the key's value.

Let us understand this better with the help of an example:

import java.util.*;
class HKR {
public static void main(String args[])
{
TreeMap<Integer, String> tm
= new TreeMap<Integer, String>();

tm.put(3, "Welcome");
tm.put(2, "to");
tm.put(1, "HKR");
for (Map.Entry mapElement : tm.entrySet()) {

int key = (int)mapElement.getKey();
String value = (String)mapElement.getValue();
System.out.println(key + " : " + value);
}
}
}

The output of this program will be:


1 : HKR
2 : to
3: Welcome

Features of Java Treemap

Below are a few features of Java Treemap:

  • The Collections Framework in Java includes this class as a component.
  • The class extends the AbstractMap class and implements the NavigableMap and SortedMap interfaces for maps.
  • Because Java's TreeMap does not support null keys (unlike Map), a NullPointerException will be raised. However, several null values could be connected to various keys.
  • The entry pairs that this class's methods and its views deliver are snapshots of the mappings as they were at the moment they were created. The method Entry.setValue is not supported by them.

                                                           Want to know more about Java,visit here Java Tutorial !

Java Certification Training

Weekday / Weekend Batches

 Conclusion

In this article, we have learned about treemaps in Java. The Java TreeMap class implements red-black trees. It offers a practical way to keep key-value pairs organized. It can also be defined as an implementation of NavigableMap based on Red-Black trees. It is arranged in the order that its keys naturally appear. We have also talked about various features of Java treemap along with the methods related to it. We have also discussed the constructors of the treemap.

Related articles:

Find our upcoming Java Certification Training Online Classes

  • Batch starts on 2nd Oct 2022, Weekend batch

  • Batch starts on 6th Oct 2022, Weekday batch

  • Batch starts on 10th Oct 2022, Weekday batch

Global Promotional Image
 

Categories

Request for more information

Amani
Amani
Research Analyst
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.

At most one null key and numerous null values may be stored in a hash map. TreeMap, on the other hand, does not permit a null key but may contain numerous null values

A method for visualizing big, hierarchical data sets is the use of treemaps. The worth of each data point and the hierarchy's structure are two different sorts of information that they extract from the data.

Java's TreeSet class implements SortedSet. Java's TreeMap class implements the Map Interface. Java's TreeSet only kept one item in storage. Two objects—one key and one value—are stored in a TreeMap.

Select Treemap from the Insert tab on the ribbon after clicking the Hierarchy symbol. To change the appearance of your chart, use the Chart Design and Format tabs. Click anywhere on the Treemap chart to activate these tabs if you can't see them.

With the help of treemaps, readers may quickly and easily analyze their data. Dimensions or measurements can be represented by a color (such as KPIs). If a KPI is being shown, a deeper hue may draw attention to extremes, either high or low.

Values in a TreeMap are depending on the key. It extends the AbstractMap class and implements the NavigableMap interface. There are just distinct components in it. While the key cannot be null, the values may include multiple nulls.