javalistjava-streamfold

Processing a collection taking two adjacent elements at a time (use of stream)


I have a list of objects that represent different cities. What I want to do with that list is obtain the sum of the distance between adjacent cities in the list. So if my list is l = {c1,c2,c3},the result would be total sum = distance(c1,c2) + distance(c2,c3).

I was trying to make use of the stream API but I couldn't find a way to process the elements on a list in this particular case where the processing is not one element at a time but involves two adjacent elements of the list at each step.

I would really appreciate if someone has any idea how to apply stream in this way, to give me a hand.


Solution

  • You can just use this:

    double distance = IntStream.range(0, cities.size() - 1)
            .mapToDouble(i -> distance(cities.get(i), cities.get(i + 1)))
            .sum();
    

    This creates an IntStream and maps the calculated distance for the neighbor cities. At the end all distance are summed up.