What is EntrySet View

What is EntrySet View

Answer: entrySet view is method in HashMap class and its signature is below:
public Set<Map.Entry<K,V>> entrySet()

  • This method returns Set view of mappings that is contained in the map
  • Set is backed by map, so changes to the map are reflected in the set and vice-versa
  • During iteration through Set if map is modified then results of the iteration are undefined
  • Set also supports removal of elements using Iterator.removeAll, retainAll, remove, Set.remove and clear operation. It don’t support addAll and add method

Example of entrySet:

package com.javahonk.hashsettest;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class EntrySetTest {

	public static void main(String[] args) {

	Map<String, Double> empMap = new HashMap<String, Double>();

	empMap.put("Java Honk", new Double(4000.55));
	empMap.put("Bob Marley", new Double(3000.33));
	empMap.put("Mike Musan", new Double(1378.00));

	// Print set of entries.
	Set<Map.Entry<String, Double>> set = empMap.entrySet();

	// Display it
	for (Map.Entry<String, Double> me : set) {
		System.out.print(me.getKey() + ": ");
		System.out.println(me.getValue());
	}

	System.out.println();

	// Withdrawn 500 by Java Honk
	double balance = empMap.get("Java Honk");
	empMap.put("John Doe", balance - 500);
	System.out.println("Java Honk total balance: " 
			+ empMap.get("John Doe"));

	}

}

 

Output:

 What is EntrySet View

Leave a Reply

Your email address will not be published. Required fields are marked *