Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum distances between points in list using Java8 Streams

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(). ...?

like image 567
MAGx2 Avatar asked Oct 22 '25 13:10

MAGx2


2 Answers

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();
like image 112
Konstantin Yovkov Avatar answered Oct 25 '25 04:10

Konstantin Yovkov


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();
like image 40
Eran Avatar answered Oct 25 '25 04:10

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!