Java stream order of processing

后端 未结 2 493
不知归路
不知归路 2021-01-13 08:37

I have the following:

LinkedList ints = new LinkedList();
//fill it with some ints
Stream stream = ints.stream();
//process the         


        
2条回答
  •  终归单人心
    2021-01-13 08:58

    Depends on the processing you are applying to the stream... especially using parallel()

    import java.util.LinkedList;
    import java.util.function.Consumer;
    import java.util.stream.Stream;
    
    public class Streaming {
    
        public static void main(String[] args) {
            LinkedList ints = new LinkedList();
            for(int i = 0 ; i < 100; i++) {
                ints.add(i);
            }
            Stream stream = ints.stream();
            // will not be ordered
            stream.parallel().forEach(new Consumer() {
    
                @Override
                public void accept(Integer t) {
                    System.out.println(t);
                }
    
            });
    
            stream = ints.stream();
            // will be ordered
            stream.parallel().forEachOrdered(new Consumer() {
    
                @Override
                public void accept(Integer t) {
                    System.out.println(t);
                }
    
            });
        }
    }
    

提交回复
热议问题