Search code examples
javaarraylistjava-streamfunctional-interface

How to use a custom functional interface with a method taking 2 arguments in an ArrayList?


@FunctionalInterface
public interface Test{

     int sum(int a, int b);

}

How can we use this sum method to add all elements of an ArrayList? Note: Want to use stream as well.

Some users have suggested that sum method is already available for this purpose; my aim was not to sum the elements of a list, it was to understand how would we use a custom functional interface on a list.


Solution

  • Assuming your functional interface's sum method return an integer, you could use the reduce method from stream. So your functional interface would be:

    @FunctionalInterface
    public interface Test{
    
        int sum(int a, int b);
    
    }
    

    And here is the example of reduce method:

    yourArraysList.stream().reduce(0, testImpl::sum);
    

    Where testImpl is an instance of the implementation of the functional interface Test.

    There's also a sum() method on stream, that deals with sum of stream's elements.

    Reference here