TreeMap entrySet() method in java

Let’s learn TreeMap entrySet() method in java.

TreeMap entrySet() method in java

entrySet() method of TreeMap class returns a Set view of the mappings contained in this map.

The set’s iterator returns the entries in ascending key order.

Syntax:

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

Parameters:

entrySet() method do not take any parameter.

Also read – TreeMap in java

Now let’s see example on TreeMap entrySet() method.

import java.util.TreeMap;
public class TreeMapEntrySetMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      // map String values to Integer keys
      tm.put(56, "mango");
      tm.put(28, "apple");
      tm.put(35, "banana");
      tm.put(73, "pineapple");
      tm.put(61, "orange");
      // printing the TreeMap
      System.out.println("Given TreeMap is: " + tm);
      // use entrySet() to get set view
      System.out.println("set view is: " + tm.entrySet());
   }
}


Output:

Given TreeMap is: {28=apple, 35=banana, 56=mango, 61=orange, 73=pineapple}
set view is: [28=apple, 35=banana, 56=mango, 61=orange, 73=pineapple]


Let’s see an example to map integer values to String keys.

import java.util.TreeMap;
public class TreeMapEntrySetMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
      // map Integer values to String keys
      tm.put("mango", 56);
      tm.put("apple", 28);
      tm.put("banana", 35);
      tm.put("pineapple", 73);
      tm.put("orange", 61);
      // printing the TreeMap
      System.out.println("Given TreeMap is: " + tm);
      // use entrySet() to get set view
      System.out.println("set view is: " + tm.entrySet());
   }
}


Output:

Given TreeMap is: {apple=28, banana=35, mango=56, orange=61, pineapple=73}
set view is: [apple=28, banana=35, mango=56, orange=61, pineapple=73]