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.

Answer from Ian Roberts on Stack Overflow
Top answer
1 of 6
164

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.

2 of 6
20

I suggest you to first try to understand Java 8 in the whole picture, most importantly in your case it will be streams, lambdas and method references.

You should never convert existing code to Java 8 code on a line-by-line basis, you should extract features and convert those.

What I identified in your first case is the following:

  • You want to add elements of an input structure to an output list if they match some predicate.

Let's see how we do that, we can do it with the following:

List<Player> playersOfTeam = players.stream()
    .filter(player -> player.getTeam().equals(teamName))
    .collect(Collectors.toList());

What you do here is:

  1. Turn your input structure into a stream (I am assuming here that it is of type Collection<Player>, now you have a Stream<Player>.
  2. Filter out all unwanted elements with a Predicate<Player>, mapping every player to the boolean true if it is wished to be kept.
  3. Collect the resulting elements in a list, via a Collector, here we can use one of the standard library collectors, which is Collectors.toList().

This also incorporates two other points:

  1. Code against interfaces, so code against List<E> over ArrayList<E>.
  2. Use diamond inference for the type parameter in new ArrayList<>(), you are using Java 8 after all.

Now onto your second point:

You again want to convert something of legacy Java to Java 8 without looking at the bigger picture. This part has already been answered by @IanRoberts, though I think that you need to do players.stream().filter(...)... over what he suggested.

🌐
TutorialsPoint
tutorialspoint.com › break-or-return-from-java-8-stream-foreach
Break or return from Java 8 stream forEach?
boolean found = names.stream().anyMatch(name -> { if (name.equals("Bob")) { // Perform action System.out.println("Found Bob"); return true; // This will short-circuit the stream } System.out.println(name); return false; }); If you?re using Java 9 or above you can use the takeWhile method to process elements until some condition is met. names.stream() .takeWhile(name -> !name.equals("Bob")) .forEach(System.out::println);
Discussions

Break or return from Java 8 stream forEach? - Stack Overflow
5 java - how to break from a forEach method using lambda expression · 2 Iterate through ArrayList with If condition and return boolean flag with stream api More on stackoverflow.com
🌐 stackoverflow.com
Getting return list from forEach java 8 - Stack Overflow
I am trying to use a stream for something and I think I have a conceptual misunderstanding. I am trying to take an array, convert it to a stream, and .forEach item in the array I want to run a func... More on stackoverflow.com
🌐 stackoverflow.com
.forEach() on a list vs .forEach() on a stream. What's the difference?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
9
5
September 29, 2023
Why does the List interface have forEach, but not map?
why isn't every List a Stream? To answer this part of the question, it's because a stream is a fundamentally different datatype than a list. A list represents a collection of data, while a stream represents a pipeline for processing data. Streams can only be processed once, and are designed to perform multiple operations on some provided data. They don't store any intermediate results, and then do lazy processing once you specify a terminal operator (like toList() or forEach()). For example, if you had something like this: Stream a = List.of(1, 2, 3).stream(); Stream b = a.filter(n -> n > 1); Stream c = b.map(n -> String.valueOf(n)); List d = c.toList(); This is functionally identical to this: List d = List.of(1, 2, 3).stream() .filter(n -> n > 1) .map(n -> String.valueOf(n)) .toList(); If you inspected b, however, it would not contain any data about what elements were remaining, because the stream has not executed yet. Assigning the various steps of the stream along the way doesn't actually DO anything to the data, it just creates pointers to instances of the pipeline. As mentioned before, the pipeline can only be executed once, which means a stream is consumed when you perform a terminal operation on it. It also can't be executed if you chain it to another pipeline. If, in the example above, you tried to do b.toList(), you'd get an IllegalStateException, because b was already operated on. If you did c.toList(), you'd get a list of "2", "3". If you did c.toList() a second time, you'd once again get an IllegalStateExcecution, because c has already been consumed. The intermediate operators like map actually do nothing except modify the pipeline definition until you call toList at the end. Once you execute toList, then the pipeline operates in a lazy way, evaluating the data elements one at a time. So, to recap: List: collection of ordered data Stream: an operation pipeline definition More on reddit.com
🌐 r/java
90
121
October 26, 2024
🌐
Stack Abuse
stackabuse.com › guide-to-java-streams-foreach-with-examples
Guide to Java Streams: forEach() with Examples
July 27, 2020 - And now, instead of basing the logic of the program on the return type, we'll perform a forEach() on the stream and add the results to an AtomicInteger (streams operate concurrently): AtomicInteger result2 = new AtomicInteger(); targetList.stream().forEach(integer -> { if (integer > 0) result2.addAndGet(1); }); System.out.println("Result: " + result2); The forEach() method is a really useful method to use to iterate over collections in Java ...
🌐
Medium
rameshfadatare.medium.com › java-stream-foreach-examples-8696ed4af274
Java Stream forEach() Examples - Ramesh Fadatare
September 27, 2024 - Here’s another real-world use case where we send an email to each user in a list using the forEach() method: import java.util.stream.Stream; public class SendEmailsExample { static class User { String email; User(String email) { this.email = email; } @Override public String toString() { return email; } } public static void main(String[] args) { Stream<User> users = Stream.of( new User("alice@example.com"), new User("bob@example.com"), new User("charlie@example.com") ); // Use forEach() to send an email to each user users.forEach(user -> System.out.println("Sending email to: " + user)); } } Output: Sending email to: alice@example.com Sending email to: bob@example.com Sending email to: charlie@example.com ·
🌐
Baeldung
baeldung.com › home › java › java collections › the difference between collection.stream().foreach() and collection.foreach()
The Difference Between stream().forEach() and forEach() | Baeldung
September 17, 2025 - If we don’t require a stream but only want to iterate over a collection, the first choice should be using forEach() directly on the collection.
🌐
Codemia
codemia.io › knowledge-hub › path › break_or_return_from_java_8_stream_foreach
Break or return from Java 8 stream forEach?
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
W3Docs
w3docs.com › java
Break or return from Java 8 stream forEach?
You can also use the anyMatch() method to find if there is any even number in the stream and return from the operation: List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); boolean result = numbers.stream() .anyMatch(n -> n % 2 == 0); System.out.println(result); // prints true · Copy · I hope this helps! Let me know if you have any questions. Tags · lambda java foreach java-8 ·
🌐
Mkyong
mkyong.com › home › java8 › java 8 foreach examples
Java 8 forEach examples - Mkyong.com
December 4, 2020 - In Java 8, we can use the new forEach to loop or iterate a Map, List, Set, or Stream.
Find elsewhere
🌐
Java67
java67.com › 2016 › 01 › how-to-use-foreach-method-in-java-8-examples.html
10 Examples of forEach() method in Java 8 | Java67
We have already seen a glimpse of the powerful feature of Stream API in my earlier post, how to use Stream API in Java 8, here we will see it again but in the context of the forEach() method. let's now only print elements that start with "a", following code will do that for you, startWith() is a method of String class, which return true if String is starting with String "a" or it will return false.
🌐
GeeksforGeeks
geeksforgeeks.org › java › stream-foreach-method-java-examples
Stream forEach() method in Java with examples - GeeksforGeeks
January 23, 2026 - import java.util.Arrays; import ... functional interface defining the operation to perform on each element. Return Value: None (void) - this is a terminal operation....
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java stream foreach()
Java Stream forEach() with Examples - HowToDoInJava
March 14, 2022 - The forEach() method is a terminal operation. It means that it does not return an output of type Stream.
🌐
Tabnine
tabnine.com › home page › code › java › java.util.stream.stream
java.util.stream.Stream.forEach java code examples | Tabnine
/** 8. Using Java 8 Stream Api parallel **/ @Benchmark public long test8_UsingJava8StreamApiParallel() throws IOException { final long[] i = {0}; map.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue()); return i[0]; }
🌐
Baeldung
baeldung.com › home › java › core java › guide to the java foreach loop
Guide to the Java forEach Loop | Baeldung
June 17, 2025 - The article is an example-heavy introduction of the possibilities and operations offered by the Java 8 Stream API. ... In Java, the Collection interface has Iterable as its super interface. This interface has a new API starting with Java 8: ... Simply put, the Javadoc of forEach states that it “performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.”
🌐
Javaprogramto
javaprogramto.com › 2020 › 05 › java-break-return-stream-foreach.html
How to Break or return from Java Stream forEach in Java 8 JavaProgramTo.com
May 13, 2020 - This method same as break or return statement in java 9 API. package com.javaprogramto.java8.streams.foreach; import java.util.Arrays; import java.util.List; public class StreamTakeWhile { public static void main(String[] args) { List<String> list = Arrays.asList("one", "two", "three", "seven", "nine"); list.stream().takeWhile(value -> value.length() > 3).forEach(value -> { if (value.length() > 3) { System.out.println(value); } }); } }
🌐
GeeksforGeeks
geeksforgeeks.org › java › foreach-loop-vs-stream-foreach-vs-parallel-stream-foreach
foreach() loop vs Stream foreach() vs Parallel Stream foreach() - GeeksforGeeks
July 12, 2025 - Java · public class GFG { public static String frechlop(String[] geek) { int count = 0; for (String var : geek) { if (count == 1) return var; count++; } return ""; } public static void main(String[] args) throws Exception { String[] arr1 = { "Geeks", "For", "Geeks" }; String secelt = frechlop(arr1); System.out.println(secelt); } } Output: For · Lambda operator is used: In stream().forEach(), lambdas are used and thus operations on variables outside the loop are not allowed.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › stream › Stream.html
Stream (Java Platform SE 8 )
2 weeks ago - Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream.
🌐
Java Guides
javaguides.net › 2020 › 04 › java-8-stream-filter-and-foreach-example.html
Java 8 Stream - filter() and forEach() Example
September 14, 2020 - Learn more about Streams at https://www.javaguides.net/p/java-8-stream-api-tutorial.html · In this example, we will create a list of products and we filter products whose price is greater than 25k. We display a list of products using the forEach() method. ... class Product { private int id; private String name; private float price; public Product(int id, String name, float price) { super(); this.id = id; this.name = name; this.price = price; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } @Override public String toString() { return "Product [id=" + id + ", name=" + name + ", price=" + price + "]"; } }