Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Interface BinaryOperator trong Java

BinaryOperator<T> là một functional interface trong package java.util.function (từ Java 8), đại diện cho một phép toán nhận 2 toán hạng cùng kiểu T và trả về kết quả cũng kiểu T.

Nó mở rộng từ BiFunction<T, T, T>.

Các phương thức static quan trọng

Modifier & Type Phương thức & Mô tả
static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) - Trả về BinaryOperator cho ra phần tử lớn hơn theo Comparator.
static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) - Trả về BinaryOperator cho ra phần tử nhỏ hơn theo Comparator.

Ví dụ 1: Dùng maxBy / minBy

import java.util.function.BinaryOperator;

public class Demo {
    public static void main(String args[]) {
        // Tìm max của 2 Integer
        BinaryOperator maxOp = BinaryOperator.maxBy((x, y) -> Integer.compare(x, y));
        System.out.println("Max(120, 5) = " + maxOp.apply(120, 5)); // 120
        
        // Tìm min
        BinaryOperator minOp = BinaryOperator.minBy(Integer::compare);
        System.out.println("Min(120, 5) = " + minOp.apply(120, 5)); // 5
    }
}

Kết quả

Max(120, 5) = 120
Min(120, 5) = 5

Ví dụ 2: Lambda expression tùy chỉnh

import java.util.function.BinaryOperator;

public class Demo {
    public static void main(String args[]) {
        // Nhân 2 số
        BinaryOperator multiply = (x, y) -> x * y;
        System.out.println("5 * 7 = " + multiply.apply(5, 7)); // 35
        
        // Nối chuỗi
        BinaryOperator concat = (s1, s2) -> s1 + s2;
        System.out.println(concat.apply("Hello, ", "World!")); // Hello, World!
        
        // Tìm chuỗi dài hơn
        BinaryOperator longer = (s1, s2) -> s1.length() >= s2.length() ? s1 : s2;
        System.out.println(longer.apply("Java", "Python")); // Python
    }
}

Kết quả

5 * 7 = 35
Hello, World!
Python

Ứng dụng thực tế: Stream.reduce()

BinaryOperator thường dùng với Stream.reduce() để tích lũy (reduce) các phần tử.

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

public class ReduceDemo {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        
        // Tổng (identity = 0)
        BinaryOperator sumOp = (a, b) -> a + b;
        int sum = numbers.stream().reduce(0, sumOp);
        System.out.println("Sum: " + sum); // 15
        
        // Tích (identity = 1)
        int product = numbers.stream().reduce(1, (a, b) -> a * b);
        System.out.println("Product: " + product); // 120
        
        // Tìm max (không cần identity nếu dùng Optional)
        int max = numbers.stream().reduce(Integer::max).orElseThrow();
        System.out.println("Max: " + max); // 5
        
        // Nối chuỗi
        List words = Arrays.asList("Java", " ", "8", " ", "Streams");
        String sentence = words.stream().reduce("", (a, b) -> a + b);
        System.out.println(sentence); // Java 8 Streams
    }
}

BinaryOperator vs BiFunction

Đặc điểmBiFunction<T, U, R>BinaryOperator<T>
Số kiểu generic3 (T, U, R)1 (T)
Kiểu tham sốCó thể khác nhau (T, U)Phải cùng kiểu (T, T)
Kiểu trả vềCó thể khác (R)Phải cùng kiểu (T)
Mối quan hệInterface chaKế thừa BiFunction<T, T, T>

Khi nào dùng BinaryOperator?

  • Phép toán hai ngôi trên cùng một kiểu: cộng, nhân, max, min, concat string, merge object...
  • Kết hợp với Stream.reduce(), Collectors.reducing(), Map.merge(), Map.compute().
  • Khi cần tính chất kết hợp (associative) để song song hóa (parallel stream).