Java에서 LinkedHashMap
을 사용할 때, 특정 값을 가진 항목을 제거하고자 하는 경우가 있습니다. 하지만 for-each
문을 사용해 직접 제거할 경우 ConcurrentModificationException
이 발생할 수 있기 때문에, 안전한 방법으로 처리하는 것이 중요합니다. 이 글에서는 특정 값(ex. 0, null, 혹은 사용자 정의 값)을 가진 항목을 안전하게 제거하는 방법을 소개합니다.
특정 값을 가진 항목 제거: Iterator 사용
LinkedHashMap
은 순서를 유지하는 특성이 있어 반복자(Iterator)를 사용하는 것이 가장 안전합니다.
예제 코드
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class RemoveSpecificValue {
public static void main(String[] args) {
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.put("apple", 10);
map.put("banana", 0);
map.put("orange", 5);
map.put("grape", 0);
map.put("melon", 3);
int targetValue = 0; // 제거하고자 하는 값
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
if (entry.getValue() == targetValue) {
iterator.remove(); // 안전하게 삭제
}
}
System.out.println(map); // 예: {apple=10, orange=5, melon=3}
}
}
주요 포인트
map.entrySet().iterator()
로 반복자를 생성- 조건을 만족하는 항목 발견 시
iterator.remove()
로 안전하게 삭제 targetValue
를 동적으로 바꾸면 유연하게 활용 가능
잘못된 방식: for-each 내부에서 직접 삭제
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
map.remove(entry.getKey()); // 예외 발생 가능
}
}
위처럼 for-each
문 안에서 remove()
를 호출하면 ConcurrentModificationException
이 발생할 수 있습니다.
활용 팁
null
, 음수, 특정 문자열 등 다양한 조건에 따라 유연하게 확장 가능- Java 8 이상에서는
removeIf
를 사용하는 방식도 있지만, 순서가 중요한LinkedHashMap
에서는Iterator
사용이 더 명확함
마무리
특정 값을 가진 항목을 삭제할 때는 단순한 반복문 대신, 반복자(Iterator)를 활용한 방식이 예외 없이 안전합니다. 이 패턴은 HashMap
, TreeMap
등 다른 Map
구현체에도 동일하게 적용할 수 있으므로 유용하게 활용하시기 바랍니다.
반응형
'개발 (Development) > Java' 카테고리의 다른 글
[Java] MyBatis foreach에서 빈 배열이 들어올 경우 예외를 방지하는 방법 (2) | 2025.07.20 |
---|---|
[Java/SpringBoot] 서버 간 API 호출 오류: Connection reset 에러 분석 및 해결 방법 (0) | 2025.07.13 |
[Java/SpringBoot] Spring OAuth2 시스템에서 발생한 Access Token 만료 및 인증 오류 대응 기록 (2) | 2025.06.28 |
[Java/SpringBoot] Spring에서 예외를 던지지 않고 API 응답은 유지하며 로그는 ERROR로 남기지 않도록 처리하는 방법 (0) | 2025.06.28 |
[Java] printStackTrace() 경고 해결 및 로깅 적용하기 (0) | 2025.06.28 |