如何解决Java Stream 减少泛型类型的 ArrayList
我不太明白 Java Stream Reduce 的工作原理。
我有一个名为“目录”的文章(通用类型)的 ArrayList。
public int getUnitsInStore()
public long getUnitPrice()
为了获得目录中所有文章的总价值,我尝试使用 Java Stream Api 的 Reduce 方法。 (请不要使用循环提供 anwser,我已经知道怎么做)
我尝试了以下操作:
long value = 0;
value = catalog.stream().reduce((a,b) -> a.getUnitPrice()*b.getUnitsInStore());
但这给了我错误:
Type mismatch: cannot convert from Optional<Article> to long
我做错了什么?正如我所说,我不确定我是否真的了解 reduce 方法的工作原理。
解决方法
累加器 lambda 中的 a
和 b
分别是部分结果和流中的下一个元素。由于您正在减少文章列表,因此部分结果是文章,您不能向文章添加 Long。
所以在你的情况下,你可能想要做这样的事情。
value = catalog.stream()
.map(a -> a.getUnitPrice() * a.getUnitsInStore())
.reduce(0L,Long::sum);
,
reduce 方法一共有三种。 试试这个代码以更好地理解它
/**
* T reduce(T identity,BinaryOperator<T> accumulator)
*
* identity = initial value
* accumulator = first process initial value to first element of the stream,* then process the result with the next element in the stream
*/
String name = Stream.of("T","O","M","Y")
.reduce("",(a,n) -> a + n);
System.out.println(name);
int sum = Stream.of(1,2,3,4,5,6,7,8,9,10)
.reduce(0,n) -> a + n);
System.out.println(sum);
int multi = Stream.of(1,10)
.reduce(1,n) -> a * n);
System.out.println(multi);
/**
* Optional<T> reduce(BinaryOperator<T> accumulator)
*
*/
Optional<String> optName = Stream.of("T","Y")
.reduce((a,n) -> a + n);
if(optName.isPresent()){
System.out.println(" get from optional --> " + optName.get());
}
/**
* <U> U reduce(U identity,BiFunction<U,? super T,U> accumulator,BinaryOperator<U> combiner)
*
* This method signature is used when we are dealing with different types.
* It allows Java to create intermediate reductions and then combine them at the end.
*/
int total = Stream.of("R","a","z","v","n")
.reduce(0,b) -> a + b.length(),(x,y) -> x + y);
// 0 = initial value type int
// a = int,must match the identity type
// b.method() return type must match the a and the identity type
// x,y from BinaryOperator
System.out.println(total);
String names[] = {"Bobby","Mark","Anthony","Danna"};
int sumAll = Stream.of(names)
.reduce(0,y) -> x + y);
System.out.println(sumAll);
String csvNames = Stream.of(names)
.reduce("",b) -> a + b + ";");
System.out.println(csvNames);
,
我建议您使用需要两个参数的 Stream.reduce()
重载:
- identity:identity 元素既是归约的初始值,也是如果流中没有元素的默认结果
- accumulator:累加器函数,它接受两个参数:减少的部分结果和流的下一个元素。它返回一个新的部分结果。
因此,您将使用以下方法获得价值:
value = catalog
.stream()
.reduce(0L,(partialSum,nextElement) -> partialSum + nextElement.getUnitPrice() * nextElement.getUnitsInStore());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。