Search code examples
javalambdafunctional-programmingfunctional-interface

Functional interface + lambda expression for sum of integers in an array


I'm tackling an exercise that asks to create a functional interface whose method takes as input an integer k and an array of integers and returns an integer. Then, I should assign to an instance of the interface a lambda expression that returns the sum off all the values in the array less than or equal to k.

For the interface I think I should do something like:

@FunctionalInterface
public interface FunctionOnAnArray {
    int apply(int k, int ... intArray);
}

However, I cannot figure out the lambda expression.

public class Test {
    int sum = 0;
    FunctionOnAnArray f = (k, intArray) -> { for (int i : intArray) if (i <= k) sum += i; return sum; };
}

This seems way too clunky.


Solution

  • You could simplify it as:

    FunctionOnAnArray f = (k, arr) -> Arrays.stream(arr)
        .filter(a -> a <= k)
        .sum();
    

    Aside: You can also choose not to define the interface with Varargs and updating it as :

    @FunctionalInterface
    public interface FunctionOnAnArray {
        int apply(int k, int[] arr);
    }