Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

BinaryOperator

A two-argument function whose arguments and result share a type.

Available since: Java 8

Syntax

@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T, T, T>

Examples

Operations for reduce():

void main() {
    BinaryOperator<Integer> max = BinaryOperator.maxBy(Comparator.naturalOrder());
    BinaryOperator<Integer> sum = Integer::sum;
    IO.println(max.apply(3, 9));
    IO.println(Stream.of(1, 2, 3).reduce(0, sum));
}

Output:

9
6

Notes

It is taken by Stream.reduce() and as the merge function of Collectors.toMap(). Ready-made operations: BinaryOperator.minBy(), BinaryOperator.maxBy(), and the references Integer::sum, Math::max.

See also

In the tutorial

  • Functional interfaces — Functional interfaces in Java: the @FunctionalInterface annotation, the standard Function, Predicate, Consumer, Supplier and combining them.

Thanks for reading!

Donate to the site — we work hard for you.