Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
    );
}
like image 614
Pedro Borges Avatar asked Feb 07 '23 06:02

Pedro Borges


1 Answers

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);
like image 134
Peter Lawrey Avatar answered Feb 16 '23 00:02

Peter Lawrey