반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 배열
- 문자열
- input
- Visual Studio Code
- 인텔리제이
- string
- 자바스크립트
- ArrayList
- Button
- Eclipse
- map
- json
- js
- IntelliJ
- vscode
- table
- 자바
- javascript
- replace
- 정규식
- 이탈리아
- date
- 이클립스
- Array
- list
- HashMap
- html
- CMD
- CSS
- Java
Archives
- Today
- Total
어제 오늘 내일
[Java HashMap] keySet(), values(), entrySet() 활용법 본문
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
를 사용
반응형
'IT > Java' 카테고리의 다른 글
[Java HashMap] clear(), size(), isEmpty() 메소드 정리 (0) | 2025.10.18 |
---|---|
[Java HashMap] forEach() 메소드와 람다식 순회 (0) | 2025.10.18 |
[Java HashMap] merge() 메소드 정리 및 활용 (0) | 2025.10.17 |
[Java HashMap] compute(), computeIfAbsent(), computeIfPresent() 메소드 정리 (0) | 2025.10.16 |
[Java HashMap] replace()와 replaceAll() 메소드 정리 (0) | 2025.10.12 |
Comments