IT

반복하는 동안 HashMap에서 키를 제거하는 방법은 무엇입니까?

lottoking 2020. 6. 13. 09:38
반응형

반복하는 동안 HashMap에서 키를 제거하는 방법은 무엇입니까? [복제]


이 질문에는 이미 답변이 있습니다.

포함하는을 ( 를) HashMap호출했습니다 .testMapString, 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 ()를 사용하십시오 .


해시 맵에서 특정 키와 요소를 제거하려면

hashmap.remove(key)

전체 소스 코드는

import java.util.HashMap;
public class RemoveMapping {
     public static void main(String a[]){
        HashMap hashMap = new HashMap();
        hashMap.put(1, "One");
        hashMap.put(2, "Two");
        hashMap.put(3, "Three");
        System.out.println("Original HashMap : "+hashMap);
        hashMap.remove(3);   
        System.out.println("Changed HashMap : "+hashMap);        
    }
}

출처 : http://www.tutorialdata.com/examples/java/collection-framework/hashmap/remove-mapping-of-specified--key-from-hashmap

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

반응형