Java8 unordered () disordering is invalid

Java8 unordered () disordering is invalid, and the result of multiple runs is still consistent with the order of the elements in the stream

/ / results of multiple runs: 5, 1, 2, 6, 3, 7, 4 did not achieve the effect of disorder
Stream.of (5, 1, 2, 6, 3, 7, 4). Unordered (). ForEach (System.out::println);
ask for advice

related codes


    /**
     * S unordered(); , , 
     */
    @Test
    public void unorderedTest() {
        Stream.of(5, 1, 2, 6, 3, 7, 4).forEach(System.out::println);
        
        // : 5, 1, 2, 6, 3, 7, 4  TODO
        Stream.of(5, 1, 2, 6, 3, 7, 4).unordered().forEach(System.out::println);
    }

May.11,2022

The

unordered () operation does nothing to explicitly stream sorting. Its purpose is to eliminate the constraint that the flow must be ordered, thus allowing subsequent operations to use optimizations that do not have to worry about sorting.

you can read this in Java 8 document :

for sequential flows, the existence of order does not affect performance, only determinism. If the flow is sequential, repeated execution of the same flow pipeline on the same source will produce the same result;
if it is a non-sequential flow, repeated execution may produce different results. For parallel flows, relaxing sorting constraints can sometimes achieve more efficient execution.

when the flow is orderly, but the user is not particularly concerned about the order, using unordered to explicitly convection to remove ordered constraints can improve the parallel performance of some stateful or terminal operations.

you can compare the following results

   Stream.of(5, 1, 2, 6, 3, 7, 4).unordered().forEach(System.out::println);
   Stream.of(5, 1, 2, 6, 3, 7, 4).unordered().parallel().forEach(System.out::println);
Menu