반응형
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
- Java
- 배열
- table
- 이탈리아
- 문자열
- 자바스크립트
- javascript
- map
- 정규식
- HashMap
- IntelliJ
- date
- string
- Array
- 이클립스
- js
- Eclipse
- vscode
- CMD
- 자바
- Visual Studio Code
- html
- Button
- ArrayList
- 인텔리제이
- json
- replace
- input
- CSS
- list
Archives
- Today
- Total
어제 오늘 내일
[Java HashMap] putIfAbsent() 메소드 활용법 본문
putIfAbsent()
는 Java 8부터 추가된 메소드로, 키가 존재하지 않을 때만 값을 넣고 싶을 때 유용합니다.
기존 값이 있다면 덮어쓰지 않고 그대로 유지합니다.
1. 기본 사용법
import java.util.HashMap;
public class HashMapPutIfAbsent {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("kim", "A");
map.putIfAbsent("kim", "B"); // 이미 있으므로 무시
map.putIfAbsent("lee", "C"); // 없으므로 추가
System.out.println(map); // {kim=A, lee=C}
}
}
같은 키가 이미 존재할 경우 값을 바꾸지 않고 기존 값을 유지합니다.
2. 반환값
import java.util.HashMap;
public class HashMapPutIfAbsentReturn {
public static void main(String[] args) {
HashMap<String, Integer> scores = new HashMap<>();
Integer prev1 = scores.putIfAbsent("kim", 90);
Integer prev2 = scores.putIfAbsent("kim", 95);
System.out.println("prev1 = " + prev1); // null (처음 삽입)
System.out.println("prev2 = " + prev2); // 90 (이미 있던 값 반환)
System.out.println(scores); // {kim=90}
}
}
리턴값은 기존 값이 있으면 그 값을 반환하고, 없으면 null
을 반환합니다.
3. 활용 예제: 기본값 초기화
import java.util.*;
public class HashMapPutIfAbsentExample {
public static void main(String[] args) {
Map<String, List<String>> groups = new HashMap<>();
groups.putIfAbsent("team1", new ArrayList<>());
groups.get("team1").add("kim");
groups.putIfAbsent("team1", new ArrayList<>()); // 무시됨
groups.putIfAbsent("team2", new ArrayList<>()); // 새로 추가
groups.get("team2").add("lee");
System.out.println(groups);
}
}
실행 결과
{team1=[kim], team2=[lee]}
그룹핑이나 리스트 초기화 같은 패턴에서 putIfAbsent
는 매우 깔끔합니다.
결론
put()
은 무조건 삽입 또는 덮어쓰기putIfAbsent()
는 키가 없을 때만 삽입, 이미 있으면 무시- 반환값으로 기존 값 확인 가능
- 기본값 세팅, 그룹핑, 캐싱 초기화 패턴에 적합
반응형
'IT > Java' 카테고리의 다른 글
[Java HashMap] replace()와 replaceAll() 메소드 정리 (0) | 2025.10.12 |
---|---|
[Java HashMap] remove() 메소드 정리 및 활용 (0) | 2025.10.11 |
[Java HashMap] get() vs getOrDefault() 차이와 활용법 (0) | 2025.10.10 |
[Java HashSet] 정렬 방법과 활용 예제 (0) | 2025.10.10 |
[Java 컬렉션] HashMap vs HashSet vs TreeSet 비교 (0) | 2025.10.09 |
Comments