Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

BinaryOperator Interface ใน Java (java.util.function)

BinaryOperator<T> เป็น Functional Interface ใน package java.util.function (Java 8+) ที่ represent operation บน operand สองตัวที่มี type เหมือนกัน และคืนค่า type เดียวกัน

extends BiFunction<T, T, T> หมายความว่า: (T, T) -> T

เมธอด Static Factory Methods

เมธอด คำอธิบาย
static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) คืน BinaryOperator ที่เลือกค่า น้อยกว่า ตาม comparator
static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) คืน BinaryOperator ที่เลือกค่า มากกว่า ตาม comparator

ตัวอย่างที่ 1: ใช้ maxBy หาค่าสูงสุด

import java.util.function.BinaryOperator;

public class Demo {
    public static void main(String[] args) {
        // ใช้ lambda expression เป็น comparator
        BinaryOperator<Integer> operator = BinaryOperator.maxBy(
            (x, y) -> (x > y) ? 1 : ((x == y) ? 0 : -1)
        );
        // หรือสั้นๆ: BinaryOperator.maxBy(Integer::compareTo)

        System.out.println(operator.apply(120, 5));  // 120
        System.out.println(operator.apply(-10, -5)); // -5
        System.out.println(operator.apply(7, 7));    // 7
    }
}

Output

120
-5
7

ตัวอย่างที่ 2: ใช้ Lambda Expression โดยตรง

import java.util.function.BinaryOperator;

public class Demo {
    public static void main(String[] args) {
        // Multiply two integers
        BinaryOperator<Integer> multiply = (x, y) -> x * y;
        System.out.println(multiply.apply(5, 7)); // 35

        // Concatenate strings
        BinaryOperator<String> concat = (s1, s2) -> s1 + s2;
        System.out.println(concat.apply("Hello, ", "World!")); // Hello, World!

        // Find longer string
        BinaryOperator<String> longer = (s1, s2) -> s1.length() >= s2.length() ? s1 : s2;
        System.out.println(longer.apply("Java", "Python")); // Python
    }
}

Output

35
Hello, World!
Python

การใช้งานกับ Stream API (Reduce)

BinaryOperator ใช้บ่อยกับ Stream.reduce()

import java.util.Arrays;
import java.util.List;
import java.util.function.BinaryOperator;

public class StreamDemo {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Sum - ใช้ lambda
        int sum = numbers.stream()
            .reduce(0, (a, b) -> a + b);
        System.out.println("Sum: " + sum); // 55

        // Max - ใช้ BinaryOperator.maxBy
        int max = numbers.stream()
            .reduce(Integer.MIN_VALUE, BinaryOperator.maxBy(Integer::compareTo));
        System.out.println("Max: " + max); // 10

        // Product
        long product = numbers.stream()
            .reduce(1L, (a, b) -> a * b);
        System.out.println("Product: " + product); // 3628800

        // String concatenation
        List<String> words = Arrays.asList("Java", " ", "is", " ", "awesome");
        String sentence = words.stream()
            .reduce("", (a, b) -> a + b);
        System.out.println(sentence); // Java is awesome
    }
}

BinaryOperator vs BiFunction vs Operator Interfaces

Interface Signature ใช้เมื่อไหร่
BinaryOperator<T> T apply(T, T) Input 2 ตัว type เดียวกัน Output type เดียวกัน
BiFunction<T,U,R> R apply(T, U) Input 2 ตัว type ต่างกันได้ Output type ต่างได้
UnaryOperator<T> T apply(T) Input 1 ตัว Output type เดียวกัน
Function<T,R> R apply(T) Input 1 ตัว Output type ต่างได้
Predicate<T> boolean test(T) Return boolean

Specialized Primitive Versions

สำหรับ primitive types มี versions แยก (หลีกเลี่ยง boxing/unboxing):

  • IntBinaryOperator - int applyAsInt(int, int)
  • LongBinaryOperator - long applyAsLong(long, long)
  • DoubleBinaryOperator - double applyAsDouble(double, double)
import java.util.function.IntBinaryOperator;

public class PrimitiveDemo {
    public static void main(String[] args) {
        IntBinaryOperator add = (a, b) -> a + b;
        System.out.println(add.applyAsInt(10, 20)); // 30 - ไม่มี boxing
    }
}