우선 일반적으로 Map 안의 값들을 반복하는 방법을 정리해보자.

 

1. For-Each Loop 사용

  • null 체크가 필요
  • keySet()으로 반복하다가 map.get(key)로 값을 꺼내는 경우 entry For-Each보다 성능 저하
// 1. entry
for (map.Entry<String, String> entry : map.entrySet()){
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

// 2. key
for (String key : map.keySet()) {
    System.out.println("Key = " + key);
}


// 3. values
for (String val : map.values()) {
    System.out.println("value = " + val);
}

2. Iterator

  • 자바 버전이 낮은 경우 사용
  • 반복 도중에 iterator.remove() 로 삭제가 가능 (For-Each에서는 에러가 발생한다.)
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();

while (entries.hasNext()) {
   Map.Entry<Integer, Integer> entry = entries.next();
   System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

왜? 반복 중에 Entry를 지울 수 없을까?

HashMap class는 동기화되지 않았기 때문이다.

동시에 entry항목을 추가하거나 제거하려고 하면 ConcurrentModificationException이 발생한다.

따라서 항목을 제거하고자 한다면 외부에 동기화 해야한다.

 

외부에서 동기화

iterator을 사용

Iterator<Entry<String, String>> iterator = foodItemTypeMap.entrySet().iterator();
while (iterator.hasNext()) {
    if (iterator.next().getKey().equals("Carrot"))
        iterator.remove();
}

자바8 이후 버전

foodItemTypeMap.entrySet()
  .removeIf(entry -> entry.getKey().equals("Grape"));

ConcurrentHashMap<K, V> 사용

java.util.concurrent.ConcurrentHashMap class를 사용하면 한번에 하나의 스레드만 사용

ConcurrentHashMap<String, String> foodItemTypeConcMap = new ConcurrentHashMap<>();
foodItemTypeConcMap.put("Apple", "Fruit");
foodItemTypeConcMap.put("Carrot", "Vegetable");
foodItemTypeConcMap.put("Potato", "Vegetable");

for (Entry<String, String> item : foodItemTypeConcMap.entrySet()) {
    if (item.getKey() != null && item.getKey().equals("Potato")) {
        foodItemTypeConcMap.remove(item.getKey());
    }
}

참고문서

Java에서 Map 관련 Iterate(반복문) 방법

 

[Java] Java에서 Map 관련 Iterate(반복문) 방법

Java에서 Map 관련하여 반복문을 사용하는 경우가 여러가지가 있다. 가장 많이 쓰이는 몇가지를 살펴보고 장단점을 알아보도록한다. Java의 모든 map들은 Map interface를 사용하므로 다음 경우들은 모

fullstatck.tistory.com

Remove an Entry from a Java HashMap

 

Remove an Entry from a Java HashMap | Baeldung

Learn different ways to remove an entry from a Java HashMap.

www.baeldung.com

 


 

entry For-Each문에서 remove를 돌리다가 알게된 것들...

'Java' 카테고리의 다른 글

캡슐화(Encapsulation) in Java  (0) 2022.10.11
PriorityQueue in Java  (0) 2022.10.10
[번역] The Basics of Java Generics  (0) 2022.10.05
Java의 날짜와 시간  (0) 2022.09.28
HashMap getOrDefault(key, defaultValue) method  (0) 2022.09.27

+ Recent posts