Last active
September 25, 2024 11:54
-
-
Save jiahut/fcbf27c46a5cd59b2ff31175eca56391 to your computer and use it in GitHub Desktop.
Difference between findAny() and findFirst() in Java 8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.concurrent.ForkJoinPool | |
| println ForkJoinPool.commonPool().getParallelism() | |
| def l = Arrays.asList("A","B","C","D") | |
| // def l = new LinkedList<String>(["B","A","C"]) | |
| println Runtime.getRuntime().availableProcessors() | |
| // def r = l.stream().parallel().filter { e -> e != "B" } .findAny() | |
| // def s = l.stream().parallel().filter { it != "B"} .findFirst() | |
| def r = l.parallelStream() | |
| .filter { e -> | |
| println "[findAny]Thread: ${Thread.currentThread().getName()}" | |
| e != "B" | |
| } | |
| .findAny() | |
| def s = l.parallelStream() | |
| .filter { e -> | |
| println "[findFirst]Thread: ${Thread.currentThread().getName()}" | |
| e != "B" | |
| } | |
| .findFirst() | |
| println l | |
| println r.get() // sometime A or C | |
| println s.get() // always A |
@jiahut Question though, if this was NOT a parallel stream, hypothetically, "findAny()" would indeed ALWAYS encounter the 'A' first, correct? Since the source is a Array (Specifically, an ORDERED collection) and the "stream" function would maintain that order, correct?
Author
in a sequential stream scenario, findAny() and findFirst() would produce identical results for this ordered collection.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perfect example! Thank you!