我有一个 Map<String, ArrayList>
和 Set<String>
.有没有办法将映射的键与字符串集“相交”,以便只保留具有给定键的对,而不遍历整个映射?我主要关心的是性能和在可以更优雅地完成的事情上重新发明轮子。
最佳答案
只要做:
map.keySet().retainAll(set);
根据 javadoc ,键集的变化会反射(reflect)在映射中。
... The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. ...
这是一个演示:
Map<String, String> map = new HashMap<String, String>();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");
Set<String> set = new HashSet<String>();
set.add("1");
set.add("3");
map.keySet().retainAll(set);
System.out.println(map); // {3=three, 1=one}
关于java - 根据其键的子集过滤 map 的元素,而无需遍历整个事物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6739129/