简体   繁体   中英

How to preserve order of the elements in streams

I want to preserve the order of array elements using below spliterator() method.

However, when I run this program it is producing 4 2 1 3 as output.

   public class Test1 {
    public static void main(String[] args) {
        m1().anyMatch(e -> {
            System.out.println(e);
            return false;
        });
    }

    private static LongStream m1() {
    return StreamSupport.longStream(Arrays.spliterator(new long[] { 1, 2, 3, 4 }), true);
    }
}

Kindly check and let me know if this thing is possible or not.

You are requesting a parallel stream, hence, you can't get a defined processing order , as parallel processing and ordered processing are a general contradiction.

If you want the elements to be processed in order, you have to do both, request a sequential stream and use a terminal operation that depends on the order:

public static void main(String[] args) {
    m1().filter(e -> {
        System.out.println(e);
        return false;
    }).findFirst();
}

private static LongStream m1() {
    return StreamSupport.longStream(Arrays.spliterator(new long[] { 1, 2, 3, 4 }), false);
}        

But note that you should avoid writing software which relies on the processing order . You should define your task in a way that the processing steps do not depend on the processing order, even if the final result may depend on the encounter order .

Eg, if you write

public static void main(String[] args) {
    m1().filter(e -> {
        System.out.println(e);
        return e%2 == 0;
    })
    .findFirst()
    .ifPresent(result -> System.out.println("final result: "+result));
}

private static LongStream m1() {
    // note that you can have it much simpler:
    return LongStream.of(1, 2, 3, 4 ).parallel();
}        

the intermediate output may be in arbitrary order and there's no guaranty whether or not you will see “3” and “4” in the output, but you have the guaranty that the last output will be “final result: 2”, as that's the first matching element in encounter order . See also here .

Well you are using anyMatch which is not preserving order in the first place, so thats pretty much expected. If you want to get the first element use findFirst for example.

As you are creating a parallel stream (second parameter = true ) StreamSupport.longStream(Arrays.spliterator(new long[] { 1, 2, 3, 4 }), true) you don't get the ordered access. If you create a sequential stream (change second parameter from true to false ) you should get what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM