How to use Java 8 streams to find all values preceding a larger value?

Using IntStream.range:

static List<Integer> findSmallPrecedingValues(List<Integer> values) {
    return IntStream.range(0, values.size() - 1)
        .filter(i -> values.get(i) < values.get(i + 1))
        .mapToObj(values::get)
        .collect(Collectors.toList());
}

It’s certainly nicer than an imperative solution with a large loop, but still a bit meh as far as the goal of “using a stream” in an idiomatic way.

Is it possible to retrieve the next value in a stream?

Nope, not really. The best cite I know of for that is in the java.util.stream package description:

The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.

(Retrieving elements besides the current element being operated on would imply they could be visited more than once.)

We could also technically do it in a couple other ways:

  • Statefully (very meh).
  • Using a stream’s iterator is technically still using the stream.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)