如何使用java 8流将列表中的值相乘 [英] How to multiply values in a list using java 8 streams

查看:997
本文介绍了如何使用java 8流将列表中的值相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

流中是否有sum()等效方法可以执行流中给出的值的乘法?

Is there a sum() equivalent method in stream which can perform multiplication of values given in a stream?

我有一个整数列表,如下所示:

I've a list of Integers like this :

List<Integer> listOfIntegers = new ArrayList<>();
listOfIntegers.addAll(Arrays.asList(1,4,2,7,5));

我能够得到所有整数的总和,但无法找到可以使用的API乘以数值并给出输出。

I'm able to get the sum of all the integers, but unable to find an API which can multiply the values and give the output.

listOfIntegers.stream().mapToInt(a -> a).sum();

如果我尝试使用forEach来执行此操作,那么我无法存储结果,因为只有最终变量是允许在里面使用。

If I try to use forEach to do it, then I cannot store the result as only final variables are allowed to be used inside it.

有没有替代方案?

推荐答案

尝试减少流量,它应该有帮助。

Try reduce of streams, it should help.

喜欢:

listOfIntegers.stream().reduce(1, (a, b) -> a * b)

链接提供了有关如何使用reduce。

This link provides more information on how to use reduce.

这篇关于如何使用java 8流将列表中的值相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆