Java/문법

Map - compute(), computeIfAbsent(), computeIfPresent()

가지코딩 2025. 4. 29. 16:34

키의 존재 여부에 따라 값을 계산하고, Map을 자동으로 갱신해주는 메서드들

  • compute()
  • computeIfAbsent()
  • computeIfPresent()

 

* Java 8부터 Map 인터페이스에 추가되었다.

  • 기존 방식
if (map.containsKey(key)) {
    map.put(key, map.get(key) + 1);
} else {
    map.put(key, 1);
}

compute() - 키가 있든 없든, 값을 저장

  • 지정한 키에 대해 값을 계산해서 저장한다.
  • 키가 이미 존재하면 그 값을 기반으로 새 값을 계산한다.
  • 키가 없어도 계산 함수는 실행된다.
  • 계산 결과가 null이면 해당 키는 Map에서 삭제된다.
V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
Map<String, Integer> map = new HashMap<>();
map.put("apple", 2);

map.compute("apple", (key, val) -> val + 1);   // 기존 값 2 → 3
map.compute("banana", (key, val) -> 1);        // 값이 없으니 1로 저장

System.out.println(map); // {apple=3, banana=1}


// 계산 결과를 null로 리턴하면 "apple" 키가 삭제됨
map.compute("apple", (key, val) -> null);

System.out.println(map); // {} ← apple 사라짐

 

 

활용 예

  • key이 처음 추가되는 경우: val = 1
  • key가 이미 map에 있으면: val = val + 1
map.compute("apple", (key, val) -> (val == null) ? 1 : val + 1);

computeIfAbsent() – 키가 없을 때만 값을 저장

  • 키가 없으면 계산 함수를 실행해 값을 저장
  • 키가 이미 있으면 아무 작업도 하지 않음
Map<String, Integer> map = new HashMap<>();
map.put("apple", 5);

map.computeIfAbsent("apple", key -> 10);   // apple 이미 존재 → 무시
map.computeIfAbsent("banana", key -> 10);  // banana 없음 → 10 저장

System.out.println(map); // {apple=5, banana=10}

computeIfPresent() – 키가 있을 때만 계산해서 수정

  • 키가 있을 때만 계산 함수 실행 후 값 수정
  • 키가 없으면 아무 일도 없음
  • 계산 결과가 null이면 해당 키 삭제
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);

map.computeIfPresent("apple", (key, val) -> val * 2); // 3 → 6
map.computeIfPresent("banana", (key, val) -> 100);    // 없음 → 무시

System.out.println(map); // {apple=6}


// computeIfPresent도 null 반환 시 키 삭제
map.computeIfPresent("banana", (key, val) -> null);

System.out.println(map); // {} ← banana 사라짐

실제 사용 예 - compute()

import java.util.HashMap;
import java.util.Map;

public class ItemPurchaseTracker {
    public static void main(String[] args) {
        Map<String, Integer> purchaseCount = new HashMap<>();

        // 아이템 구매 시 마다 호출
        trackPurchase(purchaseCount, "apple");
        trackPurchase(purchaseCount, "banana");
        trackPurchase(purchaseCount, "apple");
        
        // 출력: apple=2, banana=1
        System.out.println(purchaseCount);
    }

    public static void trackPurchase(Map<String, Integer> map, String item) {
        // 아이템을 구매할 때마다 compute()를 사용해 값 갱신
        map.compute(item, (key, count) -> (count == null) ? 1 : count + 1);
    }
}

'Java > 문법' 카테고리의 다른 글

가변 리스트 vs 불변 리스트  (1) 2025.04.29
가변 인자 (...)  (0) 2025.04.29
String.split() 문자열 자르기, 나누기  (0) 2025.04.22
어노테이션(Annotation)  (0) 2025.04.21
Enum 열거형 타입  (0) 2025.04.21