Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I modify a Map through Keyset

I am trying to apply a filter to a Map. The intention is to keep only those keys which are part of a set. The following implementation does provide the required results but I want to know if this is the right way?

private void filterProperties(Map<String, Serializable> properties, Set<String> filterSet) {
    Set<String> keys = properties.keySet();
    keys.retainAll(filterSet);
}
like image 465
The Idler Avatar asked Apr 25 '11 17:04

The Idler


2 Answers

Yes!

The set is backed by the map, so changes to the map are reflected in the set, and vice-versa

(see: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/HashMap.html#keySet())

like image 115
Itay Maman Avatar answered Oct 21 '22 02:10

Itay Maman


Itay's answer is correct, however you should make sure that properties is not modified by other threads, or is itself a thread-safe Map implementation.

If Map is not thread-safe (e.g. HashMap) and is modified by other thread you may get ConcurrentModificationException.

like image 21
Alexander Pogrebnyak Avatar answered Oct 21 '22 00:10

Alexander Pogrebnyak