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 treemapTreeMap<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
Mainclass. -
In line 4, we made a
main()function. -
In line 7, we declared a
TreeMapconsisting of keys of typeIntegerand values of typeString. -
From lines 9 to 14, we inserted values in the
TreeMapby using theTreeMap.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 theSetwith the same key-value pairs as those ofTreeMap, and we displayed it.
So, this is how to use the TreeMap.entrySet() method in Java to create a Set view of the TreeMap.