You can use peek
to verify this
== Sequential ==
Alpha1 Alpha2 Beta1 Beta2 Gamma1 Gamma2 Dolphin1 Fargo1 Fargo2 Found:
Fargo Applications: 9
== Parallel ==
Arnold1 Jim1 Loke1 Alpha1 Mustard1 Lenny1 Mustard2 Mark1 Alpha2 Mark2
Beta1 Beta2 Gamma1 Fargo1 Gamma2 Dolphin1 Fargo2 Found: Fargo
Applications: 17
YMMV depending on number of cores etc.
Produced by below
package test.test;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
public class Snippet {
static AtomicInteger predicateApplications;
public static void main(String arr[]) {
System.out.println("== Sequential == \n");
sequential();
System.out.println(" == Parallel == \n");
parallel();
}
private static void sequential() {
Stream<String> stream = Stream.of("Alpha", "Beta", "Gamma", "Dolphin", "Fargo", "Mustard", "Lenny", "Mark",
"Jim", "Arnold", "Loke");
execute(stream);
}
private static void parallel() {
Stream<String> parallelStream = Stream
.of("Alpha", "Beta", "Gamma", "Dolphin", "Fargo", "Mustard", "Lenny", "Mark", "Jim", "Arnold", "Loke")
.parallel();
execute(parallelStream);
}
private static void execute(Stream<String> stream) {
predicateApplications = new AtomicInteger(0);
Optional<String> findAny = stream.peek(s -> print(s + "1")).filter(s -> s.contains("a"))
.peek(s -> print(s + "2")).filter(s -> s.startsWith("F")).findAny();
String found = findAny.orElse("NONE");
System.out.println("\nFound: " + found);
System.out.println("Applications: " + predicateApplications.get());
}
private static void print(String s) {
System.out.print(s + " ");
predicateApplications.incrementAndGet();
}
}