Skip to content

Instantly share code, notes, and snippets.

@jiahut
Last active September 25, 2024 11:54
Show Gist options
  • Select an option

  • Save jiahut/fcbf27c46a5cd59b2ff31175eca56391 to your computer and use it in GitHub Desktop.

Select an option

Save jiahut/fcbf27c46a5cd59b2ff31175eca56391 to your computer and use it in GitHub Desktop.
Difference between findAny() and findFirst() in Java 8
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
@alpizano
Copy link

Perfect example! Thank you!

@alpizano
Copy link

@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?

@jiahut
Copy link
Author

jiahut commented Sep 25, 2024

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