@FunctionalInterface
public interface Test{
int sum(int a,int b);
}
我们如何使用这种sum方法添加ArrayList的所有元素? 注意:还要使用流。
一些用户建议sum方法已经可以用于此目的;我的目的不是要汇总列表的元素,而是要了解我们如何在列表上使用自定义功能接口。
@FunctionalInterface
public interface Test{
int sum(int a,int b);
}
我们如何使用这种sum方法添加ArrayList的所有元素? 注意:还要使用流。
一些用户建议sum方法已经可以用于此目的;我的目的不是要汇总列表的元素,而是要了解我们如何在列表上使用自定义功能接口。
假设功能接口的sum方法返回一个整数,则可以使用stream中的reduce方法。因此,您的功能界面应为:
@FunctionalInterface
public interface Test{
int sum(int a,int b);
}
这是reduce方法的示例:
yourArraysList.stream().reduce(0,testImpl::sum);
其中testImpl是功能接口Test的实现的实例。
在流上还有一个sum()方法,用于处理流元素的总和。
引用here
,假设您的功能界面如下:
@FunctionalInterface
public interface Test {
int sum(int a,int b);
}
您可以将lambda函数用于功能接口的实现(sum方法),并从流中使用reduce方法(理想情况下,如果要使用流,则不需要sum方法,因为lambda函数可以在内部直接使用减少方法):
Test test = (a,b) -> a+b;
someArrayList.stream().reduce(0,test::sum);
,
在对interface Test
实施任何操作之前,请先确定是否以及如何处理该方法的结果。在这种情况下,将不会返回任何结果,因为您已将该方法声明为void
。
您可以从一个实际返回结果并采用所需参数的方法开始:
@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))
}
}
然后在某个类中实现implements Test
或使用default
实现的方法。
请注意,多个
int
或Integer
的求和结果可能大于Integer.MAX_VALUE
和
只要没有实现interface
就没有方法,就不会编译此default
。