gegorg
gegorg

Reputation: 5

Is there a way to use a method as an input variable for another method in Java?

I attempted to create a method which calculates the sum of the values of another method in the same way the capital sigma notation does in math. I wanted it to use successive natural numbers as input variables for the function and use recursion to sum it all up. However, as I wanted to create a method for general summation, I am not sure how to assign another (single variable) method as an input variable.

I thought of something like this:

    public static int sum(int lowerbound, int upperbound, function(int x)){
        int partialsum = 0;
        for (int i = lowerbound; i <= upperbound; i++){
        partialsum = partialsum + function(i);
        }
        return partialsum;
    }

Is it possible?

Upvotes: 0

Views: 48

Answers (2)

Carcigenicate
Carcigenicate

Reputation: 45743

You pass in a IntUnaryOperator

public static int sum(int lowerbound, int upperbound, IntUnaryOperator func) { 
    ...
    partialsum += func.applyAsInt(i);

Then, either pass a method in, or use a lambda:

sum(1, 2, n -> n * 2)

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

Yes, it is possible; but you would need to pass a IntFunction (Java is not JavaScript). Like,

public static int sum(int lowerbound, int upperbound, IntFunction<Integer> function) {
    int partialsum = 0;
    for (int i = lowerbound; i <= upperbound; i++) {
        partialsum = partialsum + function.apply(i);
    }
    return partialsum;
}

And then to use it, something like

public static void main(String[] args) {
    System.out.println(sum(1, 10, a -> a));
}

Which outputs

55

It isn't clear what result you would expect (or what function you intended to pass).

Upvotes: 3

Related Questions