Java 8 Stream: How to compare current element with next element?

My free StreamEx library allows you to process the pairs of the stream elements using additional pairMap intermediate operation. Like this:

StreamEx.of(input).pairMap((current, next) -> doSomethingWith(current, next));

Where input is a Collection, array or Stream. For example, this way you can easily check whether input is sorted:

boolean isSorted = StreamEx.of(input)
                           .pairMap((current, next) -> next.compareTo(current))
                           .allMatch(cmp -> cmp >= 0);

There’s also forPairs terminal operation which is a forEach analog to all pairs of input elements:

StreamEx.of(input).forPairs((current, next) -> doSomethingWith(current, next));

These features work nicely with any stream source (either random access or not) and fully support the parallel streams.

Leave a Comment

tech