Java Remove Specific Item From ConcurrentHashMap

user4350786 picture user4350786 · Jan 9, 2015 · Viewed 11k times · Source

Is using the remove() method okay? I've read an article that synchronization hasn't been added to the remove method. How do I properly remove a specific item from a ConcurrentHashMap?

Example Code:

    ConcurrentHashMap<String,Integer> storage = new ConcurrentHashMap<String,Integer>();
    storage.put("First", 1);
    storage.put("Second", 2);
    storage.put("Third",3);


    //Is this the proper way of removing a specific item from a tread-safe collection?
    storage.remove("First");

    for (Entry<String, Integer> entry : storage.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        // ...
        System.out.println(key + " " + value);
    }

Answer

Loukan ElKadi picture Loukan ElKadi · Apr 18, 2017

An Iterator should do the job:

Iterator<Map.Entry<String, Integer>> iterator = storage.entrySet().iterator();
while(iterator.hasNext())
{
    Map.Entry<String, Integer> entry = iterator.next();
    if(entry.getKey().equals("First"))
    {
       iterator.remove();
    }
 }

Reference: https://dzone.com/articles/removing-entries-hashmap