Pedro Borges Pedro Borges - 7 months ago 8
Java Question

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

I have two methods that look very much the same:

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 wish to group these into one single helper method that takes a function as argument:

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


a, b & c are BigDecimal class fields;

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

I am running Java 8

Thank you


SOLVED


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)
);
}

Answer

You can use a Function, or in this case a BiFunction as it takes 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);
Comments