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

后端 未结 6 893
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 18:57

Use Case

Through some coding Katas posted at work, I stumbled on this problem that I\'m not sure how to solve.

Using Java 8 Streams, given a

6条回答
  •  Happy的楠姐
    2020-12-29 19:38

    Using IntStream.range:

    static List findSmallPrecedingValues(List 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.

提交回复
热议问题