어제 오늘 내일

[Java HashMap] keySet(), values(), entrySet() 활용법 본문

IT/Java

[Java HashMap] keySet(), values(), entrySet() 활용법

hi.anna 2025. 10. 17. 07:45

HashMap은 키-값 쌍을 저장하는 자료구조라서, 반복(iteration) 시 키만 가져오거나, 값만 가져오거나, 키와 값 모두 가져와야 할 때가 있습니다. 이럴 때 쓰는 대표적인 메소드가 keySet(), values(), entrySet()입니다.

 

 

1. keySet() – 키만 가져오기

import java.util.*;

public class HashMapKeySet {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("kim", 90);
        scores.put("lee", 80);
        scores.put("park", 95);

        for (String key : scores.keySet()) {
            System.out.println(key + " -> " + scores.get(key));
        }
    }
}

실행 결과

kim -> 90
lee -> 80
park -> 95

keySet()은 키 집합(Set)을 반환합니다. 키를 중심으로 값에 접근할 수 있습니다.

 

 

2. values() – 값만 가져오기

import java.util.*;

public class HashMapValues {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("kim", 90);
        scores.put("lee", 80);
        scores.put("park", 95);

        for (Integer value : scores.values()) {
            System.out.println("점수: " + value);
        }
    }
}

실행 결과

점수: 90
점수: 80
점수: 95

values()는 값만 필요할 때 유용합니다. 반환 타입은 Collection이라 중복을 허용합니다.

 

 

3. entrySet() – 키와 값 동시 접근

import java.util.*;

public class HashMapEntrySet {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("kim", 90);
        scores.put("lee", 80);
        scores.put("park", 95);

        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

실행 결과

kim = 90
lee = 80
park = 95

entrySet()Map.Entry 객체의 집합을 반환합니다. 키와 값을 동시에 꺼낼 수 있어서 가장 효율적입니다.

 

 

4. Iterator 사용 – 안전한 삭제

import java.util.*;

public class HashMapIteratorRemove {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        scores.put("kim", 90);
        scores.put("lee", 70);
        scores.put("park", 95);

        Iterator<Map.Entry<String, Integer>> it = scores.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Integer> entry = it.next();
            if (entry.getValue() < 80) {
                it.remove(); // 안전하게 삭제
            }
        }
        System.out.println(scores); // {kim=90, park=95}
    }
}

반복 도중 삭제할 경우 반드시 Iterator.remove()를 사용해야 ConcurrentModificationException을 피할 수 있습니다.

 

 

결론

  • keySet() → 키 중심 순회
  • values() → 값 중심 순회
  • entrySet() → 키-값 동시 접근 (가장 효율적)
  • 삭제 같은 구조 변경은 반드시 Iterator를 사용

 

 

반응형
Comments