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
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)
);
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With