computeIfAbsent()
키가 존재하지 않을때 해당 람다식 실행
해당 키가 존재하던 존재하지 않던 해당 value값을 리턴한다.
Map<Integer, Integer> map = new HashMap<>();
map.computeIfAbsent(1, v -> 1); //키 1이 존재하지 않으므로 1을 삽입
map.computeIfAbsent(1, v -> 2); //키 1이 이미 존재하므로 람다식 실행안됨
System.out.println("size: " + map.size());
map.forEach((k, v) -> System.out.println(k + " " + v));
size: 1
1 1
putIfAbsent()
위의 예시처럼 단순 put 연산을 할 것이라면 putIfAbsent() 메서드를 사용하는게 더 편하다.
이 메서드도 value 값 리턴한다.
Map<Integer, Integer> map = new HashMap<>();
map.putIfAbsent(1, 1);
map.putIfAbsent(1, 2);
System.out.println("size: " + map.size());
map.forEach((k, v) -> System.out.println(k + " " + v));
size: 1
1 1
computeIfPresent()
키가 존재하면 해당 람다식을 실행
해당 키에대한 value를 조작 가능. 해당 키가 존재하지 않으면 null 리턴
존재하면 람다식을 실행하고 최종 변경 결과를 리턴
Map<Integer, Integer> map = new HashMap<>();
map.putIfAbsent(1, 1);
map.computeIfPresent(1, (k, v) -> v+1);
System.out.println(map.computeIfPresent(2, (k, v) -> v+1));;
System.out.println("size: " + map.size());
map.forEach((k, v) -> System.out.println(k + " " + v));
null
size: 1
1 2
참고
null을 전달하면 해당 키가 삭제됨
Map<Integer, Integer> map = new HashMap<>();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.computeIfPresent(1, (k, v) -> null);
System.out.println("size: " + map.size());
map.forEach((k, v) -> System.out.println(k + " " + v));
size: 2
2 2
3 3
'개발 > Java' 카테고리의 다른 글
[Java] HashSet.contains() 를 사용하기 위한 @override hashcode() (0) | 2022.04.30 |
---|