BinaryOperator
BinaryOperator (이항 연산자 함수형 인터페이스)
같은 타입의 두 피연산자에 대한 연산을 나타내고, 피연산자와 같은 타입의 결과를 생성하는 함수형 인터페이스예요. 피연산자와 결과가 모두 같은 타입인 경우의 BiFunction 특수화예요.
본문
BinaryOperator<T>는 apply(T, T)를 통해 두 값을 받아 같은 타입 T의 결과를 반환해요. 사실상 BiFunction<T,T,T>와 동일해요.
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T>
정적 메서드 minBy(Comparator)와 maxBy(Comparator)는 비교자에 따라 두 인자 중 최소/최대를 반환하는 BinaryOperator를 만들어요.
BinaryOperator<Integer> max = BinaryOperator.maxBy(Integer::compare);
int m = max.apply(3, 9); // 9
Stream.reduce의 조합 함수로 자주 쓰여요.
int sum = list.stream().reduce(0, (a, b) -> a + b);
BinaryOperator<Integer> add = (a, b) -> a + b;
int total = list.stream().reduce(0, add);
함수형 메서드는 BiFunction.apply(Object, Object)예요. 코드와 시그니처는 원문 그대로 보존돼요.