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);
}
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())
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With