0

I want to delete the key having frequency 1 but i got the following error

Exception in thread "main" java.util.ConcurrentModificationExceptionat java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1495)
at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1518)
at Temp3.main(Temp3.java:14) 

How to solve it ?

import java.io.*;
import java.util.HashMap;
import java.util.*;

public class Temp3 {

    public static void main(String[] args) {
         Map<Integer, Integer> map = new HashMap();
         map.put(1,1);
         map.put(2,1);
         map.put(3,1);
         map.put(4,2);

         for(int k: map.keySet()){
             if( map.get(k) == 1){
                 map.remove(k);
             }
          }
    }
}
Hakan Dilek
  • 2,178
  • 2
  • 23
  • 35
  • While you are iterating over the map, you cannot modify it or else you will get a `ConcurrentModificationException`. Use an `Iterator` that supports remove, or temporarily copy your elements to remove to a new data structure and remove them afterwards. – Glains Jul 08 '20 at 12:17
  • 3
    Does this answer your question? [iterating over and removing from a map](https://stackoverflow.com/questions/1884889/iterating-over-and-removing-from-a-map) – bash Jul 08 '20 at 12:20

2 Answers2

2

You can use the Collection.removeIf() and the Map.values() method:

map.values().removeIf(i -> i.equals(1));

Which removes all elements from the map which are equal to 1.

Lino
  • 19,604
  • 6
  • 47
  • 65
0

The problem is that you are modifying the map while you are iterating it. Possible solutions:

import java.io.*;
import java.util.HashMap;
import java.util.*;

public class Temp3 {

    public static void main(String[] args) {
         Map<Integer, Integer> map = new HashMap();
         map.put(1,1);
         map.put(2,1);
         map.put(3,1);
         map.put(4,2);
         Integer key = null;
         for(int k: map.keySet()){
             if( map.get(k) == 1){
                 key == k;
                 break;
             }
          }
         map.remove(key);
    }
}

Or just

import java.io.*;
import java.util.HashMap;
import java.util.*;

public class Temp3 {

    public static void main(String[] args) {
         Map<Integer, Integer> map = new HashMap();
         map.put(1,1);
         map.put(2,1);
         map.put(3,1);
         map.put(4,2);

         map.remove((Integer)1);
    }
}
ddfra
  • 2,413
  • 14
  • 24