How to pass function (a, b) to a method and use it?

I have two methods that look very identical:

public Book minus(BigDecimal parameterA, BigDecimal parameterB, BigDecimal parameterC) {
    return new Book(
        this.a.subtract(parameterA),
        this.b.subtract(parameterB),
        this.c.subtract(parameterC)
    );
}

and

public Book plus(BigDecimal parameterA, BigDecimal parameterB, BigDecimal parameterC) {
    return new Book(
        this.a.add(parameterA),
        this.b.add(parameterB),
        this.c.add(parameterC)
    );
}

I want to group them into one single helper method that takes a function as an argument:

private Book apply(Function function, BigDecimal parameterA, BigDecimal parameterB, BigDecimal parameterC);

a, b and c are fields of the BigDecimal class;

Can you help me understand how I can pass such a method?

I am running Java 8

thank

solvable

public Book minus(BigDecimal parameterA, BigDecimal parameterB, BigDecimal parameterC) {
    return apply(BigDecimal::subtract, parameterA, parameterB, parameterC);
}

public Book minus(BigDecimal parameterA, BigDecimal parameterB, BigDecimal parameterC) {
    return apply(BigDecimal::add, parameterA, parameterB, parameterC);
}

private Book apply(BinaryOperator<BigDecimal> operator, BigDecimal parameterA, BigDecimal parameterB, BigDecimal parameterC) {
    return new Book(
        operator.apply(a, parameterA),
        operator.apply(b, parameterB),
        operator.apply(c, parameterC)
    );
}
+4
source share
1 answer

You can use the function, or in this case BiFunction, since it accepts two inputs or BinaryOperator, as @HankD suggests.

private Book apply(BinaryOperator<BigDecimal> function, 
                   BigDecimal parameterA,
                   BigDecimal parameterB,
                   BigDecimal parameterC);

You can call it with

Book b1 = apply(BigDecimal::add, a, b, c);
Book b2 = apply(BigDecimal::subtract, a, b, c);
+8
source

All Articles