Can a stream be processed sequentially for a part of the pipeline, and then as parallel?

I have the following code that does not work as I expected (a random line, not the first one) is skipped):

Files.lines(path)
     .skip(1)
     .parallel()
     .forEach( System.out::println )

I have the feeling that I misunderstood the behavior of Streams. The question is: can I first process the stream as sequential (and use "intermediate state operations"), and then pass it to parallel forEach?

+4
source share
4 answers

The entire conveyor is either parallel to the serial.

forEachOrdered forEach. , forEachOrdered ( forEach ).

forEach , , , .

+2

, . parallel() . sequential(), .

javaodoc :

, .

+1

, . , , Stream.skip javadocs

skip() , , n, skip (n) n , n . (, generate ()) BaseStream.unordered() skip() , . , skip() , BaseStream.sequential() .

, Files.lines(..), , Ordered. Spliterator, , , . , .

http://download.java.net/jdk8/docs/api/java/util/Spliterator.html

+1

, skip (n) n .

, [n] , Readered() BufferedReader.

Stream, , :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.stream.IntStream;

public class TestStreams {

    public static void main(String[] args) throws Exception{
         unordered();
    }

    public static void unordered() throws IOException, InterruptedException {

        StringBuilder sb = new StringBuilder();
        IntStream.range(0, 1000).forEach(n -> sb.append(n).append("\n"));

        try (BufferedReader br = new BufferedReader(new StringReader(sb.toString()))) {
            if (br.readLine() != null) {
                br.lines()
                        .parallel()
                        .forEach(it -> System.out.println(Thread.currentThread() + " : " + it));
            }
        }
    }  
}
0

All Articles