I have a Map<String,String>
with large number of key values pairs. Now I want to remove selected keys from that Map
. Following code shows what I did to achieve that.
我有一个Map
Set keySet = new HashSet(); //I added keys to keySet which I want to remove.
Then :
然后 :
Iterator entriesIterator = keySet.iterator();
while (entriesIterator.hasNext()) {
map.remove( entriesIterator.next().toString());
}
This is working. I just want to know, what would be a better way to achieve my requirement ?
这很有效。我只想知道,实现我的要求会有什么更好的方法?
2 个解决方案
#1
172
Assuming your set contains the strings you want to remove, you can use the keySet
method and map.keySet().removeAll(keySet);
.
假设您的set包含要删除的字符串,可以使用keySet方法和map.keySet()。removeAll(keySet);.
keySet
returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.keySet返回此映射中包含的键的Set视图。该集由地图支持,因此对地图的更改将反映在集中,反之亦然。
Contrived example:
举例:
Map<String, String> map = new HashMap<>();
map.put("a", "");
map.put("b", "");
map.put("c", "");
Set<String> set = new HashSet<> ();
set.add("a");
set.add("b");
map.keySet().removeAll(set);
System.out.println(map); //only contains "c"
#2
1
Just for the sake of completeness:
只是为了完整起见:
As guessed java.util.AbstractSet#removeAll
really iterates over all entries, but with one little trick: It uses the iterator of the smaller collection:
正如猜测java.util.AbstractSet#removeAll真的遍历所有条目,但有一个小技巧:它使用较小集合的迭代器:
if (size() <= collection.size()) {
Iterator<?> it = iterator();
while (it.hasNext()) {
if (collection.contains(it.next())) {
it.remove();
}
}
} else {
Iterator<?> it = collection.iterator();
while (it.hasNext()) {
remove(it.next());
}
}
#1
172
Assuming your set contains the strings you want to remove, you can use the keySet
method and map.keySet().removeAll(keySet);
.
假设您的set包含要删除的字符串,可以使用keySet方法和map.keySet()。removeAll(keySet);.
keySet
returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.keySet返回此映射中包含的键的Set视图。该集由地图支持,因此对地图的更改将反映在集中,反之亦然。
Contrived example:
举例:
Map<String, String> map = new HashMap<>();
map.put("a", "");
map.put("b", "");
map.put("c", "");
Set<String> set = new HashSet<> ();
set.add("a");
set.add("b");
map.keySet().removeAll(set);
System.out.println(map); //only contains "c"
#2
1
Just for the sake of completeness:
只是为了完整起见:
As guessed java.util.AbstractSet#removeAll
really iterates over all entries, but with one little trick: It uses the iterator of the smaller collection:
正如猜测java.util.AbstractSet#removeAll真的遍历所有条目,但有一个小技巧:它使用较小集合的迭代器:
if (size() <= collection.size()) {
Iterator<?> it = iterator();
while (it.hasNext()) {
if (collection.contains(it.next())) {
it.remove();
}
}
} else {
Iterator<?> it = collection.iterator();
while (it.hasNext()) {
remove(it.next());
}
}