TechnologyZer
technologyzer.com

Introduction to BinaryOperator Functional Interface

T apply(T t1, T t2) is an abstruct method in Binary functional interface. It takes two input and return same type of result.

public class BankAccount {
    private double balance;
    public BankAccount(double balance){
        this.balance = balance;
    }

    public double getBalance() {
        return balance;
    }

    public void transferFunds(BankAccount otherAccount, BinaryOperator<Double> transferFunction, double amount){
        this.balance = transferFunction.apply(this.balance, amount);
        otherAccount.balance = transferFunction.apply(otherAccount.balance, -amount);
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account1 = new BankAccount(1000.0);
        BankAccount account2 = new BankAccount(500.0);
        BinaryOperator<Double> transferFunction = (balance, amount) -> balance + amount;

        account1.transferFunds(account2, transferFunction, -200);
        System.out.println("Account 1 Balance: $"+account1.getBalance());
        System.out.println("Account 2 Balance: $"+account2.getBalance());
    }
}

Leave a Comment