• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Streams findAny()/findFirst()

 
Ranch Hand
Posts: 47
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi;)

I have a (simple) Question about the Stream-Mathodes findAny() and findFirst():

Why are there actually two different Method-Implementation since
findAny() also returns the first Element Java comes across?

I mean in the Study Guide on p. 191 it says about findAny():

"...it gives Java the flexibility to return to you the first element
it comes by...

I don't see the difference here I guess...


I also know what happens in this Code, but I thought,
that findAny() could return both of "ABC" and "ABCD":




I know what this Code does, but not, why always "ABC" is returned.

Kind regards
Florian
 
Saloon Keeper
Posts: 10430
223
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The difference becomes clear when you work with parallel streams. findFirst() performs an ordered traversal, and will return the first element that matches the predicate. findAny() can be performed in parallel, and will return the first element found by any thread that matches the predicate.
 
Florian Jedamzik
Ranch Hand
Posts: 47
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah I see...thank you very much Stephan!;)

Kind regards
Florian
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!