多个数求平均数java,如何使用Java 8 lambda按顺序计算多个数字的平均值

本文探讨如何使用Java 8的Lambda表达式在一个迭代中计算Point对象的x和y坐标的平均值。通过引入jOOλ库,可以实现更简洁且可复用的解决方案,或者自定义Collector来达到相同目的。
摘要由CSDN通过智能技术生成

If I have collections Point , how do I compute average of x,y using Java 8 stream on a single iteration.

Following example creates two stream & iterates twice on the input collection to compute the average of x & y. Is their any way to computer average x,y on single iteration using java 8 lambda

:

List points =

Arrays.asList(new Point2D.Float(10.0f,11.0f), new Point2D.Float(1.0f,2.9f));

// java 8, iterates twice

double xAvg = points.stream().mapToDouble( p -> p.x).average().getAsDouble();

double yAvg = points.stream().mapToDouble( p -> p.y).average().getAsDouble();

解决方案

If you don't mind using an additional library, we've added support for tuple collectors to jOOλ, recently.

Tuple2 avg = points.stream().collect(

Tuple.collectors(

Collectors.averagingDouble(p ->

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值