关于HashMap遍历时删除map中非当前遍历的键值对的问题
类似于下面的逻辑,在遍历一个hashmap中元素时,删除非当前遍历到的键值对
按照下面的两种写法,会报错
请问有没有什么遍历方法解决这种逻辑需求
at java.util.HashMap$HashIterator.nextNode(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
/**
- 类似于下面的逻辑,在遍历一个hashmap中元素时,删除非当前遍历到的键值对 按照下面的两种写法,会报错 *请问有没有什么遍历方法解决这种逻辑需求 *at java.util.HashMap$HashIterator.nextNode(Unknown Source) *at java.util.HashMap$EntryIterator.next(Unknown Source) *at java.util.HashMap$EntryIterator.next(Unknown Source) / public class Test{ public static void main(String[] args) {
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < 20; i++) {
hashMap.put(i, i);
}
// 遍历方法1
for (Iterator<Entry<Integer, Integer>> it = hashMap.entrySet().iterator(); it.hasNext();){
Entry<Integer, Integer> next = it.next();
if (hashMap.containsKey(20-next.getKey())) { // 遍历的过程中删除map中的其他key-value
hashMap.remove(20-next.getKey());
}
}
// 遍历方法2
Set<Entry<Integer,Integer>> entrySet = hashMap.entrySet();
for (Entry<Integer, Integer> entry : entrySet) {
if (hashMap.containsKey(20-entry.getKey())) {
hashMap.remove(20-entry.getKey());
}
}
}
}