我正在比较 HashMap
中的每个条目到同一个 HashMap
中的所有其他条目。迭代 HashMap
时我根据某些条件删除一些元素。然而我不断收到 ConcurrentModificationException
.
Iterator<Entry<String, String>> i = map.entrySet().iterator();
while (i.hasNext()) {
Entry<String, String> next = i.next();
for (Entry<String,String> e : map.entrySet()) {
if (e.getKey() != next.getKey()){
String[] positions_e = fields_e[1].split("-");
int start_e = Integer.parseInt(positions_e[0]);
int end_e = Integer.parseInt(positions_e[1]);
String[] positions_next = fields_next[1].split("-");
int start_next = Integer.parseInt(positions_next[0]);
int end_next = Integer.parseInt(positions_next[1]);
if (start_e <= start_next || end_e <= end_next )) {
i.remove();
}
}
}
最佳答案
将迭代器或 lambda 与removeIf 一起用于第二个循环。
for (Entry<String,String> e : map.entrySet()
)
map 迭代器:https://www.techiedelight.com/iterate-map-in-java-using-entryset/
关于java - 如何从 HashMap 中删除元素而不出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54479637/