2

Is it possible to use Java's streams to compute the (absolute) change between list members? If so, how and would it be preferable to looping (for other than aesthetic reasons)? Currently, I'm implementing this as follows:

List<Double> series; // Populated with, e.g., time series data

List<Double> seriesChanges = new ArrayList<>();

    for (int i = 1; i < series.size(); i++) {
        seriesChanges.add(Math.abs(series.get(i-1) - series.get(i)));
    }
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
basse
  • 1,088
  • 1
  • 19
  • 40
  • 4
    Yes, it is possible, but it will be more convoluted and less readable as what you have now, while still doing the same thing. – JB Nizet Apr 06 '17 at 06:40
  • 1
    AFAIK, there is no easy way to [Collect successive pairs from a stream](http://stackoverflow.com/questions/20470010/collect-successive-pairs-from-a-stream). – stholzm Apr 06 '17 at 06:49

2 Answers2

2

Slightly different solution, which does not depend on side effects on a mutable list:

IntStream.range(1, series.size())
         .mapToObj(i -> Math.abs(series.get(i - 1) - series.get(i)))
         .collect(Collectors.toList())

I can think of only one reason to use the Streams API here: it is easier to parallelize (just throw in .parallel() and maybe use an unmodifiable list... I did not try it).

stholzm
  • 3,395
  • 19
  • 31
0

Smth like this:

IntStream.range(1, series.size()).forEach(i -> seriesChanges.add(Math.abs(series.get(i - 1) - series.get(i))));

But I agree with @JB Nizet that it's really difficlut to read

Ivan Pronin
  • 1,768
  • 16
  • 14