Java.Java8.What are the functional interfaces BinaryOperator, DoubleBinaryOperator, IntBinaryOperator, and LongBinaryOperator?

A generic interface that operates on two operands of the same type and returns a result of the same type.

@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T, T, T> {
    // No additional methods
}

🧠 Example:

BinaryOperator<Integer> add = (a, b) -> a + b;
System.out.println(add.apply(5, 7)); // Output: 12

🔧 Use Case:

  • Used in reduction operations (e.g., Stream.reduce()):
List<Integer> list = List.of(1, 2, 3, 4);
int sum = list.stream().reduce(0, Integer::sum); // uses BinaryOperator

✅ 2. IntBinaryOperator

Package: java.util.function

  • Specialization for int values (primitive).
@FunctionalInterface
public interface IntBinaryOperator {
    int applyAsInt(int left, int right);
}

🧠 Example:

IntBinaryOperator multiply = (a, b) -> a * b;
System.out.println(multiply.applyAsInt(3, 4)); // Output: 12

✅ 3. LongBinaryOperator

Same as above, but for long primitives.

@FunctionalInterface
public interface LongBinaryOperator {
    long applyAsLong(long left, long right);
}

🧠 Example:

LongBinaryOperator max = (a, b) -> Math.max(a, b);
System.out.println(max.applyAsLong(10L, 20L)); // Output: 20

✅ 4. DoubleBinaryOperator

Same idea, for double primitives.

@FunctionalInterface
public interface DoubleBinaryOperator {
    double applyAsDouble(double left, double right);
}

🧠 Example:

DoubleBinaryOperator power = (a, b) -> Math.pow(a, b);
System.out.println(power.applyAsDouble(2.0, 3.0)); // Output: 8.0

🔄 Summary Table:

InterfaceInput TypesReturn Type
BinaryOperator<T>T, TT
IntBinaryOperatorint, intint
LongBinaryOperatorlong, longlong
DoubleBinaryOperatordouble, doubledouble
This entry was posted in Без рубрики. Bookmark the permalink.