如何将自定义功能接口与在 ArrayList 中采用 2 个参数的方法一起使用?

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);

}

我们如何使用这个 sum 方法来添加 ArrayList 的所有元素? 注:也想用stream。

一些用户建议 sum 方法已经可以用于此目的;我的目的不是总结列表的元素,而是了解我们如何在列表上使用自定义功能界面。

假设您的功能接口的 sum 方法 return 是一个整数,您可以使用流中的 reduce 方法。所以你的功能接口将是:

@FunctionalInterface
public interface Test{

    int sum(int a, int b);

}

这里是 reduce 方法的例子:

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

其中 testImpl 是功能接口 Test 的实现实例。

stream 上还有一个 sum() 方法,它处理 stream 元素的总和。

引用here

在你实施任何反对你的东西之前 interface Test 考虑你是否想要以及如何处理该方法的结果。在这种情况下,不会返回任何结果,因为您已将该方法声明为 void.

您可以从实际 returns 一个结果并采用所需参数的方法开始:

@FunctionalInterface
public interface Test {

    /**
     * <p>
     * Sums up all the values provided in the given list.
     * </p>
     *
     * @param list the list of numbers to be summed up
     * @return the sum of all the values
     */
    default int sum(List<Integer> list) {
        return list.stream()
                .collect(Collectors.summingInt(Integer::intValue))
    }
}

然后实现class中的方法implements Test或者使用default实现。

Note that the result of summing several ints or Integers may become greater than Integer.MAX_VALUE
and
this interface won't compile as long as there is no method without default implementation.

假设你的功能界面如下:

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

你可以使用lambda函数来实现功能接口(sum方法),并使用流中的reduce方法(如果你想使用stream,最好不需要sum方法,因为lambda函数可以直接使用在 reduce 方法中):

Test test = (a, b) -> a+b;
someArrayList.stream().reduce(0, test::sum);