Java – how should I check whether a stream is sorted?

Using Iterable < T >, it is easy to:

T last = null;
for (T t : iterable) {
    if (last != null && last.compareTo(t) > 0) {
        return false;
    }
    last = t;
}
return true;

But I can't think of a clean way to do the same thing for stream < T > This avoids consuming all elements unnecessarily

Solution

There are several ways to iterate continuous pairs of flows For example, you can view this question Of course, my favorite method is to use the library. I wrote:

boolean unsorted = StreamEx.of(sourceStream)
                           .pairMap((a,b) -> a.compareTo(b) > 0)
                           .has(true);

It is a short circuit operation: once an error is found, it will be completed Parallel flow is also good

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>