The entrySet() in Hashmap is used to get the mapping of the hashmap in a set view.
Method signature:
The signature for entrySet() is shown below:
public Set<Map.Entry<K,V>> entrySet()
Methods parameters and return type:
Parameter: It doesn’t take any parameters.
Return type: It returns a copy of a Hashmap.
Throws: N/A.
Hashmap entrySet() Example:
In this example, we have displayed a set view of a hashmap.
Source code:
public class Example1 {
public static void main(String args[]) {
HashMap map = new HashMap();
map.put(1, "This");
map.put(2, "is");
map.put(3, "a java");
map.put(4, "tutorial");
Set set = map.entrySet();
System.out.println("In a set form: " + set);
}
}
Output:
run:
In a set form: [1=This, 2=is, 3=a java, 4=tutorial]
BUILD SUCCESSFUL (total time: 0 seconds)
Example 2:
In this example, we have mapped integer values on a Hashmap. In the end, we have displayed the initial values and set form of the mapping.
Source code:
public class Example2 {
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 22);
map.put("b", 11);
map.put("c", 20);
map.put("d", 90);
map.put("e", 23);
System.out.println("Initial values: " + map);
System.out.println("The set form: " + map.entrySet());
}
}
Output:
run:
Initial values: {a=22, b=11, c=20, d=90, e=23}
The set form: [a=22, b=11, c=20, d=90, e=23]
BUILD SUCCESSFUL (total time: 1 second)