Java ConcurrentHashMap: entrySet() Example
February 09, 2022
On this page we will learn entrySet()
method of Java ConcurrentHashMap
class. A ConcurrentHashMap
is a hash table that supports full concurrency of retrievals and high expected concurrency for updates. The entrySet()
is the method of ConcurrentHashMap
with following Java doc.
Set<Map.Entry<K,V>> entrySet()
entrySet()
method returns a Set
view of map contained in this ConcurrentHashMap
.
2. If this
ConcurrentHashMap
changes, the Set
view also changes and if this Set
changes, the ConcurrentHashMap
also changes.
3. If we remove the elements from this
Set
, then the corresponding mapping is also removed from the map.
Using entrySet()
Here we will create aConcurrentHashMap
and put some contents. Then we call entrySet()
method on it. Using for loop, we iterate the set.
ConcurrentHashMap<String, Integer> conMap = new ConcurrentHashMap<>(); conMap.put("Mahesh", 22); conMap.put("Nilesh", 25); conMap.put("Krishn", 20); conMap.put("Pradeep", 23); Set<Entry<String, Integer>> entrySet = conMap.entrySet(); for (Map.Entry<String, Integer> mapEntry : entrySet) { System.out.println(mapEntry.getKey() + " " + mapEntry.getValue()); }
Krishn 20 Mahesh 22 Pradeep 23 Nilesh 25
Remove Element
The element can be removed usingIterator.remove
, Set.remove
and Set.removeIf
methods.
The changes in
Set
view also perform the corresponding changes in ConcurrentHashMap
.
Now find the ways to remove the elements.
1. Using
Iterator.remove
Iterator<Map.Entry<String, Integer>> iterator = conMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, Integer> entry = iterator.next(); if (entry.getValue() == 20) { iterator.remove(); } } System.out.println(conMap);
{Mahesh=22, Pradeep=23, Nilesh=25}
Set.remove
Set<Entry<String, Integer>> entrySet = conMap.entrySet(); for (Map.Entry<String, Integer> mapEntry : entrySet) { if (mapEntry.getKey().equals("Nilesh")) { entrySet.remove(mapEntry); } } System.out.println(conMap);
{Krishn=20, Mahesh=22, Pradeep=23}
Set.remove
Set<Entry<String, Integer>> entrySet = conMap.entrySet(); entrySet.removeIf(e -> e.getKey().equals("Krishn")); System.out.println(conMap);
{Mahesh=22, Pradeep=23, Nilesh=25}