I have a list of points (x,y) and I want to sum the distances between them. In old Java I would do it like this:
List<Point> points = ...
long sum = 0;
for (int i = 0; i < points.size() - 1; i++) {
sum += PointUtil.distance(points.get(i), points.get(i + 1));
}
return sum;
Now the question is: can I do the same code using points.stream(). ...?
Yes. You can use IntStream, in order to have indexing:
long sum = IntStream.range(0, points.size() - 1)
.mapToLong(i -> PointUtil.distance(points.get(i), points.get(i + 1)))
.sum();
Here's the first thing I could think of:
sum = IntStream.range(0,points.size()-1)
.mapToLong(i -> PointUtil.distance(points.get(i), points.get(i + 1)))
.sum();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With