How to check whether Java stream is ordered?

Herosław Miraszewski :

Is it possible to check if a Java Stream is ordered or not?

By unordered Stream I mean, for instance a stream on which unordered() was called.

Lyashko Kirill :

In order to check if a stream is unordered you need to get characteristics of stream's spliterator and test is 3th bit is set to one.

You can use this code snippet as an example:

    Stream<Integer> sorted = Stream.of(1, 2, 3).sorted();
    System.out.println((sorted.spliterator().hasCharacteristics(Spliterator.SORTED));

    sorted = Stream.of(1, 2, 3).sorted().unordered();
    System.out.println((sorted.spliterator().hasCharacteristics(Spliterator.SORTED));

    Stream<Integer> unordered = Stream.of(1, 2, 3).unordered();
    System.out.println((unordered.spliterator().hasCharacteristics(Spliterator.SORTED));

    unordered = Stream.of(1, 2, 3);
    System.out.println((unordered.spliterator().hasCharacteristics(Spliterator.SORTED));

For more details you can check Spliterator documentation.

UPDATE: But invocation of spliterator() is a terminal operation on the stream, what means that no more operations can be performed on it. In spite of that the elements will nor be consumed, what makes it possible to create new stream with the same characteristics in way:

    Spliterator<Integer> spliterator = unordered.spliterator();
    System.out.println(spliterator.hasCharacteristics(Spliterator.SORTED));
    Stream<Integer> newStream = StreamSupport.stream(spliterator, unordered.isParallel())
                                             .onClose(unordered::close); // in case if you have some close handlers on initial stream

Thanks @Holger for pointing the last moment.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=8625&siteId=1