PHpullh
학습 라이브러리/Java/BiFunction과 BinaryOperator

JAVA · 람다/메서드

BiFunction과 BinaryOperator

두 개의 인자를 받는 함수형 인터페이스를 활용합니다.

람다/메서드중급BiFunctionBinaryOperatorMap.merge함수형

핵심 설명

두 개의 인자를 받는 함수형 인터페이스를 활용합니다.

Java code

import java.util.*;
import java.util.function.*;

public class BiFunctionDemo {
    public static void main(String[] args) {
        // BiFunction<T, U, R> — 2개 인자, 1개 반환
        BiFunction<String, Integer, String> repeat =
            (s, n) -> s.repeat(n);
        System.out.println(repeat.apply("Ha", 3)); // HaHaHa

        // BinaryOperator<T> — 같은 타입 2개 -> 같은 타입
        BinaryOperator<Integer> max = Integer::max;
        System.out.println(max.apply(10, 20)); // 20

        // Map.merge에서 BinaryOperator 사용
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Alice", 80);
        scores.merge("Alice", 90, Integer::max);
        System.out.println(scores.get("Alice")); // 90

        // Map.compute
        Map<String, List<String>> groups = new HashMap<>();
        BiFunction<String, List<String>, List<String>> append =
            (key, val) -> {
                if (val == null) val = new ArrayList<>();
                val.add("new-" + key);
                return val;
            };
        groups.compute("A", append);
        groups.compute("A", append);
        System.out.println(groups); // {A=[new-A, new-A]}
    }
}

학습 팁

Map.merge(), Map.compute()에서 BiFunction을 활용하면 null 처리 로직을 깔끔하게 작성할 수 있습니다.

주의할 점

BiFunction에는 compose()가 없고 andThen()만 있습니다. 합성 시 주의하세요.

자주 묻는 질문

BiFunction과 BinaryOperator란 무엇인가요?

두 개의 인자를 받는 함수형 인터페이스를 활용합니다.

BiFunction과 BinaryOperator 학습 시 주의할 점은 무엇인가요?

BiFunction 에는 compose() 가 없고 andThen() 만 있습니다. 합성 시 주의하세요.