given Map hashMap 和 Set hashset,当set的key出现在map里面时,删除Map 里面的元素,最后返回map. public void modifyMap(Map hashmap, Set hashset) { } 面试官说3行就可以搞定,那位大侠说说?
g8
2 楼
Consumer prices rose less than expected in January, while prices excluding food and energy fell for the first time since 1982, soothing worries inflation pressures were starting to build up.
exclude food and energy, what a joke Good news for GOLD though.
【在 g8 的大作中提到】 : : Consumer prices rose less than expected in January, while prices excluding : food and energy fell for the first time since 1982, soothing worries : inflation pressures were starting to build up.
题目是要求保留key 出现在 set 里的元素,这个不是删除了这些元素么? 我觉得是正确的是这样: public void modifyMap(Map hashmap, Set hashset){ for (K key: hashmap.keySet()){ if (!hashset.contains(key)) hashmap.remove(key); } }
这种方法会抛出ConcurrentModificationException异常,因为迭代过程中不允许修改 hashmap的state /** given Map hashMap 和 Set hashset,当set的key出现在map里面时,保留Map 里面的元素,最后返回map. */ import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class SetAndMap { public static void main(String args[]){ Map
【在 f********a 的大作中提到】 : given Map hashMap 和 Set hashset,当set的key出现在map里面时,删除Map : 里面的元素,最后返回map. : public void modifyMap(Map hashmap, Set hashset) : { : } : 面试官说3行就可以搞定,那位大侠说说?
j*w
15 楼
public void modifyMap(Map hashmap, Set hashset) { Iterator it = hashmap.entrySet().iterator(); while (it.hasNext()) { Entry entry = (Entry) it.next( );
if (hashset.contains(entry.getKey())) continue; else hashmap.remove(it); } }
z*e
16 楼
Set tempSet = new HashSet(map.keySet()); tempSet.removeAll(set); for(K k:tempSet) map.remove(k); 这里有个陷阱,考java里面的reference 第一行很重要,一定要new,否则会出问题
说3行就3行: public void modifyMap(Map hashmap, Set hashset) { Iterator> it = hashmap.entrySet().iterator(); while (it.hasNext()) if (!hashset.contains(it.next().getKey())) it.remove(); }