반응형
반복하는 동안 HashMap에서 키를 제거하는 방법은 무엇입니까? [복제]
이 질문에는 이미 답변이 있습니다.
- 반복 및지도에서 제거 [중복] 12 답변
포함하는을 ( 를) 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 ()를 사용하십시오 .
해시 맵에서 특정 키와 요소를 제거하려면
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);
}
}
참고 URL : https://stackoverflow.com/questions/6092642/how-to-remove-a-key-from-hashmap-while-iterating-over-it
반응형
'IT' 카테고리의 다른 글
html“select”요소의 옵션 스타일을 지정하는 방법은 무엇입니까? (0) | 2020.06.13 |
---|---|
ASP.NET Identity의 기본 암호 해셔-어떻게 작동하며 안전합니까? (0) | 2020.06.13 |
도커 컨테이너를 실행할 때 서비스를 자동으로 시작하는 방법은 무엇입니까? (0) | 2020.06.13 |
Swift에서 수학적 PI 상수를 얻는 방법 (0) | 2020.06.13 |
Intellij IDEA의 System.out.println () 바로 가기 (0) | 2020.06.13 |