개발언어/JAVA
[JAVA] Map - putIfAbsent 이란? 사용방법 및 예제
코딩 시그널
2021. 10. 29. 19:57
반응형
putIfAbsent
- Key 값이 존재하는 경우 Map의 Value의 값을 반환하고, Key값이 존재하지 않는 경우 Key와 Value를 Map에 저장하고 Null을 반환합니다.
사용방법
default V putIfAbsent(K key, V value)
매개변수
- key - 지정된 값이 연관될 키
- value - 지정된 키와 연결될 값
반환 값
- key 값이 존재하는 경우 > Map의 value 값을 반환
- key 값이 존재하지 않는 경우 > key와 value를 Map에 저장하고 null을 반환
기본 구현은 다음과 같습니다.
V v = map.get(key);
if (v == null)
v = map.put(key, value);
return v;
예제
package testProject;
import java.util.HashMap;
public class putIfAbsentTest {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("A", 1);
map.put("B", 1);
map.put("C", 1);
map.put("D", null);
System.out.println("result : " + map.toString());
//result : {A=1, B=1, C=1, D=null}
map.putIfAbsent("E", 1);
System.out.println("result1 : " + map);
//result1 : {A=1, B=1, C=1, D=null, E=1}
map.putIfAbsent("E", 2);
System.out.println("result2 : " + map);
//result2 : {A=1, B=1, C=1, D=null, E=1}
map.putIfAbsent("D", 1);
System.out.println("result3 : " + map);
//result3 : {A=1, B=1, C=1, D=1, E=1}
}
}
결과
HashMap의 경우 키가 존재하지 않거나 value의 값의 null인 경우 Value에 값을 넣어주는 것을 확인할 수 있습니다.