关于HashMap遍历时删除map中非当前遍历的键值对的问题?

关于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());
        }
    }

}
}

这没办法啊,你要是删除当前键值对还有办法,你这样remove绝对会报错,
不管是删除当前还是其他键值对.你只能找个list存下key,value遍历完之后删除
删除当前键值对的写法要用迭代器的remove,具体原因可以自行搜索,涉及到集合底层逻辑

        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < 20; i++) {
            map.put(i, i);
        }
        Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, Integer> entry = it.next();
            Integer key = entry.getKey();
            if (key % 2 == 0) {
                it.remove();
            }
        }
        System.out.println(map);