What is the TreeMap.entrySet() method in Java?

In this shot, we will learn how to use the TreeMap.entrySet()method in Java. This method is present in the TreeMap class inside the java.util package.

The TreeMap.entrySet() method is used to create a new set and store the elements of the TreeMap. In other words, it creates a Set view of the TreeMap.

Syntax

The syntax of the TreeMap.entrySet() method is shown below:

Set<Map.Entry<K,V>> entrySet();

Parameter

The TreeMap.entrySet() method does not accept any parameters.

Return

The TreeMap.entrySet() method returns a Set with the same elements as that of the TreeMap.

Code

Let’s have a look at the code.

import java.util.*;
class Main
{
public static void main(String[] args)
{
//Creating a treemap
TreeMap<Integer, String> s = new TreeMap<Integer,String>();
s.put(2, "Learn");
s.put(12, "in-demand");
s.put(31, "tech");
s.put(18, "skills");
s.put(25, "on");
s.put(36, "Educative.io");
//Displaying the treemap without using entrySet()
System.out.println("TreeMap mappings are: "+ s);
//Displaying the treemap using entrySet()
System.out.println("The set after using entrySet() method is:" + s.entrySet());
}
}

Explanation:

  • In line 1, we imported the required package.

  • In line 2, we made a Main class.

  • In line 4, we made a main() function.

  • In line 7, we declared a TreeMap consisting of keys of type Integer and values of type String.

  • From lines 9 to 14, we inserted values in the TreeMap by using the TreeMap.put() method.

  • In line 17, we displayed the mappings that are present in the TreeMap.

  • In line 19, we used the TreeMap.entrySet() method to obtain the Set with the same key-value pairs as those of TreeMap, and we displayed it.

So, this is how to use the TreeMap.entrySet() method in Java to create a Set view of the TreeMap.