Skip to content

Commit a38ef41

Browse files
add a stream example
1 parent 75ac905 commit a38ef41

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package java_streams;
2+
3+
import java.util.Arrays;
4+
import java.util.List;
5+
6+
public class StreamsExample {
7+
public static void main(String... args) {
8+
/**reference: https://www.baeldung.com/java-when-to-use-parallel-stream*/
9+
System.out.println("Program started.");
10+
sequentialStreams();
11+
parallelStreams();
12+
System.out.println("Program ended.");
13+
}
14+
15+
private static void sequentialStreams() {
16+
/**By default, any stream operation in Java is processed sequentially, unless explicitly specified as parallel.
17+
Sequential streams use a single thread to process the pipeline like below:
18+
*/
19+
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
20+
listOfNumbers.stream().forEach(number ->
21+
System.out.println(number + " from this thread: " + Thread.currentThread().getName())
22+
);
23+
}
24+
25+
private static void parallelStreams() {
26+
/**
27+
* Any stream in Java can easily be transformed from sequential to parallel.
28+
* We can achieve this by adding the parallel method to a sequential stream or by creating a stream using the parallelStream method of a collection:
29+
* */
30+
List<Integer> listOfNumbers = Arrays.asList(5, 6, 7, 8);
31+
listOfNumbers.parallelStream().forEach(number ->
32+
System.out.println(number + " from this thread: " + Thread.currentThread().getName())
33+
);
34+
/**
35+
* Parallel streams enable us to execute code in parallel on separate cores.
36+
* The final result is the combination of each individual outcome.
37+
* However, the order of execution is out of our control.*/
38+
39+
/**
40+
* Parallel streams make use of the fork-join framework and its common pool of worker threads.
41+
* The fork-join framework was added to java.util.concurrent in Java 7 to handle task management between multiple threads.*/
42+
}
43+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy