How is this method used? What is it used for? Normally all collection views (including keySet()) do not allow add and addAll methods - because I cannot add any key without respective value. Sorry, but I do not understand API and how to use this method. Could anyone please give a clear example? Does it mean that if I add myNewKey to such key set, then (myNewKey, mappedValue) key-value binding is added to respective (original) map?
public ConcurrentHashMap.KeySetView keySet(V mappedValue)
Returns a Set view of the keys in this map, using the given common mapped value for any additions (i.e., Collection.add(E) and Collection.addAll(Collection)). This is of course only appropriate if it is acceptable to use the same value for all additions from this view.
Normally all collection views (including keySet()) do not allow add and addAll methods - because I cannot add any key without respective value
This is not the case here. Adding elements to keySet(V mappedValue)
is equivalent to putting in the Map
new keys associated with the value mappedValue
.
if I add myNewKey to such key set, then (myNewKey, mappedValue) key-value binding is added to respective (original) map?
That's correct.
ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
Set<String> keySet = map.keySet("sameValue");
keySet.add("key1");
keySet.add("key2");
will result in the same Map
as:
ConcurrentHashMap<String,String> map = new ConcurrentHashMap<>();
map.put("key1","sameValue");
map.put("key2","sameValue");