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