Home  >  Core Java

Java ConcurrentHashMap: entrySet() Example

By Arvind Rai, 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() 
1. The 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 a ConcurrentHashMap 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());
} 
Output
Krishn 20
Mahesh 22
Pradeep 23
Nilesh 25 

Remove Element

The element can be removed using Iterator.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); 
Output
{Mahesh=22, Pradeep=23, Nilesh=25} 
2. Using 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); 
Output
{Krishn=20, Mahesh=22, Pradeep=23} 
3. Using Set.remove
Set<Entry<String, Integer>> entrySet = conMap.entrySet();
entrySet.removeIf(e -> e.getKey().equals("Krishn"));
System.out.println(conMap); 
Output
{Mahesh=22, Pradeep=23, Nilesh=25} 

Reference

Java ConcurrentHashMap
POSTED BY
ARVIND RAI
ARVIND RAI










©2022 concretepage.com | Privacy Policy | Contact Us