javalambdajava-8java-stream

How to calculate differences in a list of integers using lambda expressions


Lets say I have the following array: {1,2,3,4,6,7,8} which is put in a Stream<Integer> s = Stream.of(1,2,3,4,6,7,8);

How can I use in Java lambda expressions and Stream functions to calculate the difference between each element and the next (in this case {1,1,1,2,1,1})? This is not really a reduce operation as reduce transforms the entire list to 1 element; it also isn't a map operation as it requires two elements to calculate the difference and not just one.


Solution

  • You can loop over the indices instead of the elements, e.g.

    int s[] = {1, 2, 3, 4, 6, 7, 8};
    IntStream differences = 
        IntStream.range(0, s.length - 1)
            .map(i -> s[i + 1] - s[i]);