접근
map[type] -> 자바는 map을 배열처럼 접근할 수 없다
무조건 map.get(key) or map.put(key,value) 사용해야한다.
put()
put(key,value)
- 해당 key가 이미 존재하면 → value를 덮어씌웁니다. (기존 값이 새 값으로 바뀜)
- 해당 key가 없으면 → 새로 추가
반환값은 기존 값이다.
Integer oldValue = map.put("apple", 10);
System.out.println(oldValue); // 이전 값인 5 출력
📚 putIfAbsent vs getOrDefault 차이
putIfAbsent(key, value) | 키가 없으면 value를 넣고, 있으면 무시 | 값 덮어쓰기 원하지 않을 때 |
getOrDefault(key, defaultValue) | 키가 있으면 기존 값 반환, 없으면 기본값 반환 | 값 조회할 때 안전하게 기본값 설정 |
1️⃣ putIfAbsent(key, value)
"이 키가 없으면 value를 넣고, 있으면 아무것도 하지 마라."
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.putIfAbsent("apple", 5); // apple 키가 이미 있으므로 무시
map.putIfAbsent("banana", 2); // banana 키가 없으므로 추가됨
System.out.println(map.get("apple")); // 3
System.out.println(map.get("banana")); // 2
- "apple"은 이미 존재하니까 기존 값 3 유지
- "banana"는 없었으니까 2 추가
🔵
기존 값을 덮어쓰고 싶지 않을 때 사용합니다.
2️⃣ getOrDefault(key, defaultValue)
"이 키가 있으면 그 값 주고, 없으면 기본값을 주자."
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 3);
int a = map.getOrDefault("apple", 0); // apple 있으면 값 가져옴 (3)
int b = map.getOrDefault("banana", 0); // banana 없으면 기본값 0 가져옴
System.out.println(a); // 3
System.out.println(b); // 0
🔵
키가 있을지 확실하지 않을 때 안전하게 조회할 때 사용합니다.
(NullPointerException 걱정 없이!)
코테 유형별 정리
1️⃣ "Map을 깔끔하게 값 증가시키는 공식"
문제 상황
- 어떤 값이 이미 Map에 있으면 +1 하고
- 없으면 처음 1로 추가하고 싶을 때
(예: 단어 개수 세기, 의상 종류 개수 세기 등)
✅ 가장 깔끔한 공식
map.put(key, map.getOrDefault(key, 0) + 1);
- map.getOrDefault(key, 0) :
키가 있으면 기존 값 가져오고, 없으면 0 반환 - +1 :
거기에 1 더해서 - map.put(key, 그 결과) :
다시 저장
📚 예시 코드
HashMap<String, Integer> map = new HashMap<>();
String[] words = {"apple", "banana", "apple", "orange", "banana", "apple"};
for (String word : words) {
map.put(word, map.getOrDefault(word, 0) + 1);
}
// 결과 출력
for (String key : map.keySet()) {
System.out.println(key + " : " + map.get(key));
}
apple : 3
banana : 2
orange : 1
✅ 알아서 존재하는 키는 +1, 없는 키는 1로 새로 추가됨!
2️⃣ "Grouping, Counting 문제를 Map으로 푸는 공식 패턴"
문제 상황
- 어떤 그룹(예: 카테고리, 타입, 문자 종류 등)별로 개수를 세고 싶을 때
- 또는 그룹핑해서 리스트를 묶고 싶을 때
✅ 기본적인 Counting 패턴
for (데이터 : 데이터들) {
String 그룹 = 그룹을 구하는 방법;
map.put(그룹, map.getOrDefault(그룹, 0) + 1);
}
(위에서 배운 값 증가 패턴과 거의 같음)
📚 예시: 의상 종류별 개수 세기
HashMap<String, Integer> map = new HashMap<>();
// 입력: (이름, 종류)
String[][] clothes = {
{"yellowhat", "headgear"},
{"bluesunglasses", "eyewear"},
{"green_turban", "headgear"}
};
for (String[] item : clothes) {
String type = item[1];
map.put(type, map.getOrDefault(type, 0) + 1);
}
// 결과 출력
for (String type : map.keySet()) {
System.out.println(type + " : " + map.get(type));
}
headgear : 2
eyewear : 1
✅ "종류"별로 몇 개 있는지 정확히 카운팅됨.
✅ 고급: 그룹별로 "리스트"로 묶기 (Grouping)
만약 그냥 개수만이 아니라,
그룹별로 데이터를 리스트로 묶고 싶으면?
HashMap<String, List<String>> groupMap = new HashMap<>();
for (String[] item : clothes) {
String name = item[0];
String type = item[1];
groupMap.putIfAbsent(type, new ArrayList<>());
groupMap.get(type).add(name);
}
// 결과 출력
for (String type : groupMap.keySet()) {
System.out.println(type + " : " + groupMap.get(type));
}
headgear : [yellowhat, green_turban]
eyewear : [bluesunglasses]
✅ 종류별로 어떤 옷들이 있는지 리스트로 묶을 수 있습니다!
🔥 최종 요약
그룹별 개수 세기 | map.put(key, map.getOrDefault(key, 0) + 1); |
그룹별로 데이터 묶기 | map.putIfAbsent(key, new ArrayList<>()); map.get(key).add(데이터); |
'PS > JAVA' 카테고리의 다른 글
입력 (0) | 2025.04.27 |
---|---|
타입 추론 (0) | 2025.04.10 |
System.out.println() (0) | 2025.04.10 |
Array Vs List (0) | 2025.04.10 |
size() vs .length (0) | 2025.04.10 |