putIfAbsent

- Key 값이 존재하는 경우 : Map의 value 값 반환

- Key 값이 존재하지 않는 경우 : Key와 value 를 Map 에 저장하고 Null 을 반환

 

 

매개변수

- key : 지정된 값이 연관될 키

- value : 지정된 키와 연결될 값

 

 

기본 예제

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}
	}
}

 

'JAVA' 카테고리의 다른 글

정렬과 lambda  (0) 2022.09.29
PriorityQueue ( 우선순위큐 )  (0) 2022.09.27
Java의 이중 중괄호 초기화  (0) 2022.08.11
HashSet  (0) 2022.08.11
Stream  (0) 2022.08.10

+ Recent posts