java - 如何从 HashMap 中删除元素而不出现 ConcurrentModificationException

标签 java hashmap java-7 concurrentmodification

我正在比较 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/

map 的 Lambda:https://javarevisited.blogspot.com/2017/08/how-to-remove-key-value-pairs-from-hashmap-java8-example.html#axzz5eHbDQxwp

关于java - 如何从 HashMap 中删除元素而不出现 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54479637/

相关文章:

java - 通过 Java 使用 SQLXMLBulkload

java - HashMap 值未附加到 ListView

用于唯一对象实例的 Java Map?

Java:从命令行运行时重定向内部进程输出

java - Hibernate池似乎释放了连接

java - 为什么下面的代码不起作用?

Java 8 性能对比。 Java 7

java - 在 Java 中实现定时器事件的最简单方法

c# - 正则表达式匹配 CSV 文件

java - 字符串缓冲区 : Adding a newline after a certain amount of words for formatting