WeakHashMap Set keySet() method Example Program

Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Program

```package com.candidjava;

import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;

/*
* @author : Mohan
* @description : The keySet() method is used to return a set view of the keys contained in this map.
*/
public class WeakHashMapKeySet {
public static void main(String[] args) {
Map<String, String> weakHashMap = new WeakHashMap<String, String>();

weakHashMap.put("1", "anandh");
weakHashMap.put("2", "hari");
weakHashMap.put("3", "vinoth");
weakHashMap.put("4", "kamal");
weakHashMap.put("5", "karthic");
weakHashMap.put("6", "mohan");
System.out.println("Contents of the Map" + weakHashMap);
Set set = weakHashMap.keySet();
System.out.println("Contents of the set");
System.out.println(set);
}
}
```

Output

Contents of the Map{4=kamal, 5=karthic, 6=mohan, 1=anandh, 2=hari, 3=vinoth}
Contents of the set
[4, 5, 6, 1, 2, 3]

Explanation

public Set<K> keySet()
Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
Specified by:
keySet in interface Map<K,V>
Overrides:
keySet in class AbstractMap<K,V>
Returns:
a set view of the keys contained in this map

Related Post