-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJava8StreamsExample.java
More file actions
47 lines (36 loc) · 1.31 KB
/
Java8StreamsExample.java
File metadata and controls
47 lines (36 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package challenge1.java8;
import externalLegacyCodeNotUnderOurControl.PriceService;
import java.util.HashSet;
import java.util.OptionalDouble;
import java.util.Set;
import static externalLegacyCodeNotUnderOurControl.PrintlnWithThreadname.println;
/**
* This example uses parallel streams which are available since Java 8.
*
* @author Marcus Fihlon, www.fihlon.ch
*/
public class Java8StreamsExample {
private static final int NUMBER_OF_SERVICE_CALLS = 10;
private final Set<PriceService> services;
public static void main(final String... args) {
new Java8StreamsExample().run();
}
/**
* Create the price services.
*/
private Java8StreamsExample() {
this.services = new HashSet<>();
for (int i = 0; i < NUMBER_OF_SERVICE_CALLS; i++) {
this.services.add(new PriceService());
}
}
/**
* Use parallel streams to calculate the average price of all price services.
*/
private void run() {
final OptionalDouble average = this.services.parallelStream()
.mapToInt(PriceService::getPrice) // this call is executed in parallel
.average(); // this call blocks because it needs all answers from the price services to calculate
println("The average price is: " + average.orElseGet(null));
}
}