어제 오늘 내일

[Java HashMap] compute(), computeIfAbsent(), computeIfPresent() 메소드 정리 본문

IT/Java

[Java HashMap] compute(), computeIfAbsent(), computeIfPresent() 메소드 정리

hi.anna 2025. 10. 16. 07:43

Java 8부터 HashMap에 추가된 compute 계열 메소드는 키의 현재 값(또는 null)을 바탕으로 새로운 값을 계산해 저장합니다. 동적 갱신 패턴에서 매우 유용합니다.

 

1. compute(K key, BiFunction<K, V, V> remappingFunction)

import java.util.HashMap;

public class HashMapCompute {
    public static void main(String[] args) {
        HashMap<String, Integer> scores = new HashMap<>();
        scores.put("kim", 90);

        scores.compute("kim", (k, v) -> v + 10);   // 기존 값 90 → 100
        scores.compute("lee", (k, v) -> v == null ? 70 : v + 10); // 키 없으면 기본값 70

        System.out.println(scores); // {kim=100, lee=70}
    }
}

기존 값이 있으면 계산식으로 갱신, 없으면 null이 들어와 기본값을 넣을 수 있습니다.

 

2. computeIfAbsent(K key, Function<K, V> mappingFunction)

import java.util.HashMap;

public class HashMapComputeIfAbsent {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("id1", "Alice");

        map.computeIfAbsent("id1", k -> "Default"); // 이미 있음 → 무시
        map.computeIfAbsent("id2", k -> "Bob");     // 없음 → 새로 계산 후 저장

        System.out.println(map); // {id1=Alice, id2=Bob}
    }
}

키가 없을 때만 계산해서 값을 넣습니다. putIfAbsent와 비슷하지만, 단순 값이 아니라 계산된 값도 넣을 수 있습니다.

 

3. computeIfPresent(K key, BiFunction<K, V, V> remappingFunction)

import java.util.HashMap;

public class HashMapComputeIfPresent {
    public static void main(String[] args) {
        HashMap<String, Integer> scores = new HashMap<>();
        scores.put("kim", 90);

        scores.computeIfPresent("kim", (k, v) -> v + 5); // 존재하면 갱신
        scores.computeIfPresent("lee", (k, v) -> v + 5); // 없음 → 무시

        System.out.println(scores); // {kim=95}
    }
}

키가 존재할 때만 계산해 값을 갱신합니다.

 

4. 활용 예제: 단어 빈도수 세기

import java.util.*;

public class HashMapWordCount {
    public static void main(String[] args) {
        String text = "apple banana apple cherry banana apple";
        String[] words = text.split(" ");

        Map<String, Integer> freq = new HashMap<>();
        for (String word : words) {
            freq.compute(word, (k, v) -> (v == null) ? 1 : v + 1);
        }

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

compute()를 활용하면 값이 없을 때는 1로 초기화하고, 있으면 +1 하면서 간결하게 빈도수를 셀 수 있습니다.

 

결론

  • compute → 키의 현재 값 기반으로 새 값 계산 (없으면 null)
  • computeIfAbsent → 키 없을 때만 계산 후 저장
  • computeIfPresent → 키 있을 때만 계산 후 갱신
  • 조건부 갱신, 동적 초기화, 카운팅 패턴에 유용

 

 

반응형
Comments