Close

Java 8 Streams - LongStream.parallel Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.LongStream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.LongStreamLongStreamLogicBig

Method:

LongStream parallel()

This intermediate operation returns an equivalent stream that is parallel. It may return itself, either because the stream was already parallel, or because the underlying stream state was modified to be parallel.

Examples


package com.logicbig.example.longstream;

import java.util.stream.LongStream;

public class ParallelExample {

public static void main(String... args) {
System.out.println("-- parallel --");
LongStream stream = LongStream.of(4, 7, 9, 11, 13, 17);
stream.parallel()
.forEach(System.out::println);

System.out.println("-- sequential --");
LongStream stream2 = LongStream.of(4, 7, 9, 11, 13, 17);
stream2.forEach(System.out::println);
}
}

Output

-- parallel --
11
13
17
9
7
4
-- sequential --
4
7
9
11
13
17




package com.logicbig.example.longstream;

import java.util.stream.LongStream;

public class ParallelExample3 {

public static void main(String... args) {

System.out.println("-- sequential --");
LongStream stream2 = LongStream.range(1, 10);
stream2.sequential()
.forEach(ParallelExample3::work);

System.out.println("-- parallel --");
LongStream stream = LongStream.range(1, 10);
stream.parallel()
.forEach(ParallelExample3::work);

}

private static void work(long l) {
try {
Thread.sleep(200);
System.out.printf("working with %s, active threads %s%n", l,
Thread.activeCount());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Output

-- sequential --
working with 1, active threads 1
working with 2, active threads 1
working with 3, active threads 1
working with 4, active threads 1
working with 5, active threads 1
working with 6, active threads 1
working with 7, active threads 1
working with 8, active threads 1
working with 9, active threads 1
-- parallel --
working with 6, active threads 8
working with 8, active threads 8
working with 2, active threads 8
working with 7, active threads 8
working with 3, active threads 8
working with 1, active threads 8
working with 9, active threads 8
working with 4, active threads 8
working with 5, active threads 8




See Also