If you need this, you shouldn't use forEach, but one of the other methods available on streams; which one, depends on what your goal is.

For example, if the goal of this loop is to find the first element which matches some predicate:

Optional<SomeObject> result =
    someObjects.stream().filter(obj -> some_condition_met).findFirst();

(Note: This will not iterate the whole collection, because streams are lazily evaluated - it will stop at the first object that matches the condition).

If you just want to know if there's an element in the collection for which the condition is true, you could use anyMatch:

boolean result = someObjects.stream().anyMatch(obj -> some_condition_met);
Answer from Jesper on Stack Overflow
Discussions

Return from lambda forEach() in java - Stack Overflow
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. ... If you want to return a boolean value, then ... More on stackoverflow.com
🌐 stackoverflow.com
How can Stream forEach method accept boolean?
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
12
3
April 3, 2023
lambda - Java how to use stream map to return boolean - Stack Overflow
Start a chat to get instant answers from across the network. Sign up to save and share your chats. Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Closed 7 years ago. I am trying to return a boolean for the result. public boolean status(List myArray) { boolean statusOk = false; myArray.stream().forEach... More on stackoverflow.com
🌐 stackoverflow.com
java - Iterate through ArrayList with If condition and return boolean flag with stream api - Stack Overflow
I am trying to make myself more comfortable with Java 8 Stream api. Currently I want to translate something like as stream, but it seems I am still not comfortable enough, because I have no idea h... More on stackoverflow.com
🌐 stackoverflow.com
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.

🌐
Reddit
reddit.com › r/learnjava › how can stream foreach method accept boolean?
r/learnjava on Reddit: How can Stream forEach method accept boolean?
April 3, 2023 -

Hi, studying for Java 17 certificate. Came to this question:

void brew() throws IOException {
 final var m = Path.of("coffee");
 Files.walk(m)
      .filter(Files::isDirectory)
      .forEach(Files::isDirectory);
}

I see a boolean supplied for forEach() method. My answer was "Does not compile". But it actually does compile. I dont get why. If I try forEach(true) it does not compile. So how does code in the example compile? forEch() accepts Consumer<>, not boolean :?

Top answer
1 of 4
6
In your example Files::isDirectory is passed to the forEach method,which is not a boolean, but a static method reference (which happens to return a boolean). You can provide a reference to a method which has a non-void return value as an argument wherever the a Consumer is expected - this might have caught you off guard - but the return value is simply discarded.
2 of 4
1
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.
🌐
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 ·
🌐
Blogger
javarevisited.blogspot.com › 2015 › 09 › java-8-foreach-loop-example.html
Java 8 forEach() Loop Example
listOfPrimes.stream().filter(i ... just one method which returns boolean type, hence you can use a lambda expression which returns boolean in place of Predicate....
Find elsewhere
🌐
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 - package com.javaprogramto.java8.streams.foreach; import java.util.Spliterator; import java.util.function.BiConsumer; import java.util.stream.Stream; public class CustomForEachImpl { public static class Break { private boolean doBreak = false; public void stop() { doBreak = true; } boolean get() { return doBreak; } } public static <T> void forEach(Stream<T> stream, BiConsumer<T, Break> consumer) { Spliterator<T> spliterator = stream.spliterator(); boolean hadNext = true; Break breaker = new Break(); while (hadNext && !breaker.get()) { hadNext = spliterator.tryAdvance(elem -> { consumer.accept(elem, breaker); }); } } }
🌐
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.
🌐
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);
🌐
Medium
raphaeldelio.medium.com › why-wont-my-foreach-lambda-allow-me-to-exit-my-function-with-a-return-statement-986792e9c054
Why won't my forEach lambda allow me to exit my function with a return statement in Java? | by Raphael De Lio | Medium
January 25, 2024 - In this implementation, you can see that under the hood, the forEach function is using a for each loop, performing the given action and not returning anything. So to satisfy our operation in a functional approach, we will need to find another lambda. There is a good candidates here: allMatch. With the allMatch lambda, we can check if all of the elements of the basket is a fruit: private boolean onlyFruits(List<Food> basket) { return basket.stream().allMatch(food -> food.getFoodType() == FRUIT); }
🌐
Baeldung
baeldung.com › home › java › java streams › how to break from java stream foreach
How to Break from Java Stream forEach | Baeldung
January 25, 2024 - While providing a Stream with the break mechanism embedded can be useful, it may be simpler to focus on just the forEach operation. Let’s use the Stream.spliterator directly without a decorator: public class CustomForEach { public static class Breaker { private boolean shouldBreak = false; public void stop() { shouldBreak = true; } boolean get() { return shouldBreak; } } public static <T> void forEach(Stream<T> stream, BiConsumer<T, Breaker> consumer) { Spliterator<T> spliterator = stream.spliterator(); boolean hadNext = true; Breaker breaker = new Breaker(); while (hadNext && !breaker.get()) { hadNext = spliterator.tryAdvance(elem -> { consumer.accept(elem, breaker); }); } } }
🌐
Linus Tech Tips
linustechtips.com › software › programming
Java - For Each Loop and Boolean Help Please - Programming - Linus Tech Tips
June 9, 2016 - Hi there, I'm looking for help on how to do this part... I'm completely new to Java and learning bit by bit. My goal for this thread today is: "isValidState () is a private method you must write which contains a local ArrayList of the 50 United States state names, and returns true if the String p...
🌐
Baeldung
baeldung.com › home › java › core java › guide to the java foreach loop
Guide to the Java forEach Loop | Baeldung
June 17, 2025 - Introduced in Java 8, the forEach() method provides programmers with a concise way to iterate over a collection. In this tutorial, we’ll see how to use the forEach() method with collections, what kind of argument it takes, and how this loop differs from the enhanced for-loop.
🌐
Hackajob
hackajob.com › talent › blog › the-benefits-of-the-collection-api-in-java-8-part-1
The Benefits of the Collection API in Java 8: Part 1
October 9, 2023 - The ‘removeIf’ method has been added to Java 8’s Collection interface, with this method accepting a single argument which is a ‘Predicate’ instance. ‘Predicate’ is an in-built functional interface that accepts an argument of any data type and returns a boolean.
🌐
javaspring
javaspring.net › blog › return-from-lambda-foreach-in-java
Java Lambda forEach(): Why Returning a Value Doesn't Work (And What to Use Instead)
However, it is not designed to return values, thanks to its dependency on the Consumer functional interface (which returns void). To return values from collection processing, use Java streams’ built-in operations: