How should I check whether a Stream<T> is sorted?

How should I check whether a Stream<T> is sorted?

Related searches

With an Iterable<T>, it's easy:

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 a Stream<T> that avoids consuming all the elements when it doesn't have to.


There are several methods to iterate over the successive pairs of the stream. For example, you can check this question. Of course my favourite method is to use the library I wrote:

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

It's short-circuit operation: it will finish as soon as it find the misorder. Also it works fine with parallel streams.

Do we need to check if a Stream in java 8 if it is null and not iterate , No, it's not necessary�. As long as you use empty Streams instead of null (for example as method parameters), everything works just fine. To see if your PC can stream onto to twitch, you need to check the benchmarks for your CPU, testing the x246 criteria. The reason we are only looking at the benchmark for x246 encoding is because that is the most important ability of the CPU during a stream You can see your CPUs score by clicking here, and using Ctrl + F to find your CPU.


You can grab the Stream's underlying spliterator and check it it has the SORTED characteristic. Since it's a terminal operation, you can't use the Stream after (but you can create another one from this spliterator, see also Convert Iterable to Stream using Java 8 JDK).

For example:

Stream<Integer> st = Stream.of(1, 2, 3);
//false
boolean isSorted = st.spliterator().hasCharacteristics(Spliterator.SORTED);

Stream<Integer> st = Stream.of(1, 2, 3).sorted();
//true
boolean isSorted = st.spliterator().hasCharacteristics(Spliterator.SORTED);

My example shows that the SORTED characteristic appears only if you get the Stream from a source's that reports the SORTED characteristic or you call sorted() at a point on the pipeline.

One could argue that Stream.iterate(0, x -> x + 1); creates a SORTED stream, but there is no knowledge about the semantic of the function applied iteratively. The same applies for Stream.of(...).

If the pipeline is infinite then it's the only way to know. If not, and that the spliterator does not report this characteristic, you'd need to go through the elements and see if it does not satisfy the sorted characteristic you are looking for.

This is what you already done with your iterator approach but then you need to consume some elements of the Stream (in the worst case, all elements). You can make the task parallelizable with some extra code, then it's up to you to see if it's worth it or not...

Check if an array contains specified value in Java, In this post, we will see how to check if a primitive or an object array contains specified value or not in Java. We can use Java 8 Stream API to check if.. Should I choose the medical or engineering (non-medical) in Science Stream? So you have to take the decision whether you want to take the medical stream or the engineering (non-medical) stream. There is an option between Biology and Mathematics in schools in Class 11th.


You could hijack a reduction operation to save the last value and compare it to the current value and throw an exception if it isn't sorted:

.stream().reduce((last, curr) -> {
   if (((Comparable)curr).compareTo(last) < 0) {
       throw new Exception();
    }

    return curr;
});

EDIT: I forked another answer's example and replaced it with my code to show it only does the requisite number of checks.

http://ideone.com/ZMGnVW

Tired of Null Pointer Exceptions? Consider Using Java SE 8's , You don't need to write complex nested conditions to check for null. In addition In other words, all the separate streams that are generated by the function get� You can grab the Stream's underlying spliterator and check it it has the SORTED characteristic. Since it's a terminal operation, you can't use the Stream after (but you can create another one from this spliterator, see also Convert Iterable to Stream using Java 8 JDK).


This is a sequential, state holding solution:

IntStream stream = IntStream.of(3, 3, 5, 6, 6, 9, 10);
final AtomicInteger max = new AtomicInteger(Integer.MIN_VALUE);
boolean sorted = stream.allMatch(n -> n >= max.getAndSet(n));

Parallelizing would need to introduce ranges. The state, max might be dealt with otherwise, but the above seems most simple.

Part 2: Processing Data with Java SE 8 Streams, In the first part of this series, you saw that streams let you process collections with For instance, you can combine flatMap and collect to produce a Map as a value in the Map , you need to check whether a list has been created, and so on. Does anyone else have a wee chuckle at the endless positivity of the emails from stream elements. Great stream there you are down 3 viewers from the last stream, keep grinding. Or You are up 2 viewers from the last stream thats 200% increase! Keep going. I am a small streamer and i find this quite funny.


You could use allMatch with a multi-line lambda, checking the current value against the previous one. You'll have to wrap the last value into an array, though, so the lambda can modify it.

// infinite stream with one pair of unsorted numbers
IntStream s = IntStream.iterate(0, x -> x != 1000 ? x + 2 : x - 1);
// terminates as soon as the first unsorted pair is found
int[] last = {Integer.MIN_VALUE};
boolean sorted = s.allMatch(x -> {
    boolean b = x >= last[0]; last[0] = x; return b; 
});

Alternatively, just get the iterator from the stream and use a simple loop.

Check if a String starts with any of the given prefixes in Java , Below are the following approaches that can be used to complete the given task: Using loop, iterate through the prefixes and check whether the string starts with the Convert the Prefixes into Stream using Stream.of(); Check if any prefix� In that stream alone, we had a peak of about 50,000 viewers and we concurrently kept between 40 to 30,000 viewers, and then it ended up fizzling out around 10,000. When you’re in that situation where you have some collaboration from a developer, that’s when you want to stream as much as you can.


You should know how to check the speed of your home internet connection so that you are getting what you pay for. then technically only one device at a time is able to stream at that speed.


Using Binary Search Method:. In this, search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.


Check the quality that Netflix is streaming at. If it says 4K, then it should be streaming at 4K. Check network statistics, if you’re using over 15Mb/s of downstream (download) internet, then you should be streaming at 4K. Just remember you need a 4K monitor to take full advantage of 4K.