What is KeySet View

What is KeySet View

Answer: keySet view is method in HashMap class.
This method returns Set view of all keys that is contained in map. Below is important point of KeySet:

  • Any chages in the map will be reflected to the Set and vice-versa.
  • If map is getting modified during iteration over the set are in progress (except using iterator’s own remove operation) then results of iteration are undefined.
  • Note: Set supports element removal operation through which it removes corresponding mapping from the map, via Set.remove, Iterator.remove, removeAll, retainAll, and clear operations. It does not supports add and addAll methods.

Please see below example for KeySet:

package com.javahonk.setTest;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class KeySetTest {

	public static void main(String[] args) {

	Map<String,String> map = 
			new ConcurrentHashMap<String, String>();

	map.put("Java", "Java");
	map.put("Honk", "Honk");
	map.put("Test", "Test");	

	System.out.println("Pring value Set:\n");
	Set<String> keySet = map.keySet();

	System.out.println(keySet);
	System.out.println("\nPring value using iterator:\n");
	Iterator<String> iterator = map.keySet().iterator();
	while(iterator.hasNext()) {
		String key = (String)iterator.next();
		String val = (String)map.get(key);	    
		map.put("New value","New value");
	    System.out.println("Key:" + key 
	    		+ "  Value: " + val);		    
	}

	}

}

 

Output:
What is KeySet View

Leave a Reply

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