The return
there is returning from the lambda expression rather than from the containing method. Instead of forEach
you need to filter
the stream:
players.stream().filter(player -> player.getName().contains(name))
.findFirst().orElse(null);
Here filter
restricts the stream to those items that match the predicate, and findFirst
then returns an Optional
with the first matching entry.
This looks less efficient than the for-loop approach, but in fact findFirst()
can short-circuit - it doesn't generate the entire filtered stream and then extract one element from it, rather it filters only as many elements as it needs to in order to find the first matching one. You could also use findAny()
instead of findFirst()
if you don't necessarily care about getting the first matching player from the (ordered) stream but simply any matching item. This allows for better efficiency when there's parallelism involved.