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);
}
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
.
your code looks good. You can write a single line as properties.keySet().retainAll(filterSet);
One problem I see is that the map could be un-modifiable. If that's a possibility then maybe building a new map with original entry set and then filtering and returning it will be a better option.
精彩评论