IT이야기

반복하는 동안 해시맵에서 키를 제거하는 방법

cyworld 2022. 5. 20. 21:40
반응형

반복하는 동안 해시맵에서 키를 제거하는 방법

나는 가지고 있다.HashMap불렀다testMap그 안에 들어 있는String, String.

HashMap<String, String> testMap = new HashMap<String, String>();

지도를 반복할 때,value지정된 문자열과 일치한다. 맵에서 키를 제거해야 한다.

for(Map.Entry<String, String> entry : testMap.entrySet()) {
  if(entry.getValue().equalsIgnoreCase("Sample")) {
    testMap.remove(entry.getKey());
  }
}

testMap포함하다"Sample"그러나 나는 키를 제거할 수 없다.HashMap.
대신 오류:

"Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
    at java.util.HashMap$EntryIterator.next(Unknown Source)
    at java.util.HashMap$EntryIterator.next(Unknown Source)"

시도:

Iterator<Map.Entry<String,String>> iter = testMap.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String,String> entry = iter.next();
    if("Sample".equalsIgnoreCase(entry.getValue())){
        iter.remove();
    }
}

Java 1.8 이상에서는 다음 작업을 한 줄에 걸쳐 수행할 수 있다.

testMap.entrySet().removeIf(entry -> "Sample".equalsIgnoreCase(entry.getValue()));

Iterator.remove()를 사용하십시오.

참조URL: https://stackoverflow.com/questions/6092642/how-to-remove-a-key-from-hashmap-while-iterating-over-it

반응형