No.

You could use a while loop instead.

Iterator iterator = list.iterator();
while(iterator.hasNext()) {
    ...
}
Answer from NimChimpsky on Stack Overflow
Top answer
1 of 2
1

You can make something like this instead.

  • Filter the student list for the condition you need.
  • Then using the forEach to produce a side effect (printing the eligibles names in this example).

Here it is more readable and without the nesting if:

  List<Student> eligables =
                studentList_2
                        .stream()
                        .filter(s -> studentList_1.contains(s) && getEligibility(s.getMajor()))
                        .collect(Collectors.toList());
eligables.forEach(s -> System.out.println("Eligible for doctor :: " + s.getName()));
2 of 2
0

Firstly, you need to create a stream using Collection.stream() method.

To retain only students contained in the second list and to check the major property of a student, You can use filter() operation.

Note: that you need to implement equals/hashCode contract in order to compare Student objects based on their properties.

And to make contains() check more performant, you can dump the student from the second list into a HashSet.

That's how it might be implemented:

List<Student> studentList1 = // initializing list1
        
List<Student> studentList2 = // initializing list2
        
Set<Student> toCheck = new HashSet<>(studentList2);

studentList2.stream()
    .filter(toCheck::contains)
    .filter(student -> student.getMajor().equals("pcb"))
    .map(Student::getName)
    .forEach(name -> System.out.println("Eligible for doctor :: " + name));

You might want to store these name, that's how it can be done

List<String> isEligibleForDoctorNames = studentList2.stream()
    .filter(toCheck::contains)
    .filter(student -> student.getMajor().equals("pcb"))
    .map(Student::getName)
    .collect(Collectors.toList());
🌐
CodingTechRoom
codingtechroom.com › question › exit-foreach-java-8-conditional
How Can I Exit a forEach Loop in Java 8 If a Condition Is Met? - CodingTechRoom
In Java 8, the forEach method from the Stream API does not provide a direct way to break out of the loop like a traditional for loop.
🌐
Java67
java67.com › 2016 › 01 › how-to-use-foreach-method-in-java-8-examples.html
10 Examples of forEach() method in Java 8 | Java67
One of the main features of Stream API is its capability to filter elements based upon some conditions. 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.
Top answer
1 of 5
122

Just put the condition into the lambda itself, e.g.

animalMap.entrySet().stream()
        .forEach(
                pair -> {
                    if (pair.getValue() != null) {
                        myMap.put(pair.getKey(), pair.getValue());
                    } else {
                        myList.add(pair.getKey());
                    }
                }
        );

This can be simplified and made more readable using Map.forEach, as suggested by Jorn Vernee:

animalMap.forEach(
        (key, value) -> {
            if (value != null) {
                myMap.put(key, value);
            } else {
                myList.add(key);
            }
        }
);

Of course, these solutions assume that both collections (myMap and myList) are declared and initialized prior to the above pieces of code.

2 of 5
18

In most cases, when you find yourself using forEach on a Stream, you should rethink whether you are using the right tool for your job or whether you are using it the right way.

Generally, you should look for an appropriate terminal operation doing what you want to achieve or for an appropriate Collector. Now, there are Collectors for producing Maps and Lists, but no out of-the-box collector for combining two different collectors, based on a predicate.

Now, this answer contains a collector for combining two collectors. Using this collector, you can achieve the task as

Pair<Map<KeyType, Animal>, List<KeyType>> pair = animalMap.entrySet().stream()
    .collect(conditional(entry -> entry.getValue() != null,
            Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
            Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
Map<KeyType,Animal> myMap = pair.a;
List<KeyType> myList = pair.b;

But maybe, you can solve this specific task in a simpler way. One of you results matches the input type; it’s the same map just stripped off the entries which map to null. If your original map is mutable and you don’t need it afterwards, you can just collect the list and remove these keys from the original map as they are mutually exclusive:

List<KeyType> myList=animalMap.entrySet().stream()
    .filter(pair -> pair.getValue() == null)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

animalMap.keySet().removeAll(myList);

Note that you can remove mappings to null even without having the list of the other keys:

animalMap.values().removeIf(Objects::isNull);

or

animalMap.values().removeAll(Collections.singleton(null));

If you can’t (or don’t want to) modify the original map, there is still a solution without a custom collector. As hinted in Alexis C.’s answer, partitioningBy is going into the right direction, but you may simplify it:

Map<Boolean,Map<KeyType,Animal>> tmp = animalMap.entrySet().stream()
    .collect(Collectors.partitioningBy(pair -> pair.getValue() != null,
                 Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Map<KeyType,Animal> myMap = tmp.get(true);
List<KeyType> myList = new ArrayList<>(tmp.get(false).keySet());

The bottom line is, don’t forget about ordinary Collection operations, you don’t have to do everything with the new Stream API.

🌐
Dev.java
dev.java › learn › refactoring-to-functional-style › foreachwithif
Converting foreach with if
Copyright © 2026 Oracle and/or its affiliates. All rights reserved. Terms of Use | Privacy | Trademarks
🌐
Javaprogramto
javaprogramto.com › 2020 › 05 › java-break-return-stream-foreach.html
How to Break or return from Java Stream forEach in Java 8
May 13, 2020 - New stream api introduced with takeWhile(Predicate<T> p) method which stops once the condition is met then it stops iterating through the remaining elements. So, it returns a new Stream until the condition is met. 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); } }); } }
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › using ‘if-else’ conditions with java streams
Using 'if-else' Conditions with Java Streams - HowToDoInJava
March 3, 2022 - ArrayList<Integer> numberList = new ArrayList<>(Arrays.asList(1,2,3,4,5,6)); Predicate<Integer> isEven = i -> i % 2 == 0; numberList.stream() .filter(isEven) .forEach(System.out::println); Using one of the above given two methods, we can apply any combination of if-else conditions in Java 8 stream elements.
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › core java › guide to the java foreach loop
Guide to the Java forEach Loop | Baeldung
June 17, 2025 - Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time. ... Introduced in Java 8, the forEach() method provides programmers with a concise way to iterate over a collection.
🌐
Mkyong
mkyong.com › home › java8 › java 8 foreach examples
Java 8 forEach examples | mkyong.com
December 4, 2020 - package com.mkyong.java8.misc; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; public class ForEachWriteFile { public static void main(String[] args) { ForEachWriteFile obj = new ForEachWriteFile(); obj.save(Paths.get("C:\\test"), obj.createDummyFiles()); } public void save(Path path, List<DummyFile> files) { if (!Files.isDirectory(path)) { throw new IllegalArgumentException("Path must be a directory"); } files.forEach(f -> { try { int id = f.
🌐
Ecocraftplanet
ecocraftplanet.com › does-someone › java-8-foreach-if-condition.html
Java 8 foreach if condition
In given nbsp 18 Mar 2020 First ... predicate the condition to select nbsp In Java 8 we have a newly introduced forEach method to iterate over forEach key value gt if key 4 System....
🌐
Learn IT University
learn-it-university.com › home › exploring java foreach loops with conditional statements
Exploring Java Foreach Loops with Conditional Statements - Learn IT University
June 29, 2024 - However, there might be situations where you need to iterate over a collection and also apply a condition during each iteration. This can be achieved by combining Java's foreach loop with an if statement.
🌐
CodingTechRoom
codingtechroom.com › question › java-foreach-loop-conditions
How to Use Java Foreach with Conditions in a Loop - CodingTechRoom
Use an 'if' statement within the foreach loop to apply a condition to each item. Consider using Streams for more complex conditions and filtering requirements.
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › java-8-foreach
Java 8 forEach method with example
*/ hmap.forEach((key,value)->System.out.println(key+" - "+value)); /* forEach to iterate a Map and display the value of a particular * key */ hmap.forEach((key,value)->{ if(key == 4){ System.out.println("Value associated with key 4 is: "+value); } }); /* forEach to iterate a Map and display the key associated with a * particular value */ hmap.forEach((key,value)->{ if("Cat".equals(value)){ System.out.println("Key associated with Value Cat is: "+key); } }); } } ... In this example, we are iterating an ArrayList using forEach() method. Inside forEach we are using a lambda expression to print eac
🌐
Benchresources
benchresources.net › home › java › java 8 – stream foreach() method with examples
Java 8 - Stream forEach() method with examples - BenchResources.Net
May 25, 2022 - We are applying condition to filter out only EVEN numbers using filter() method · Finally, printing to console using Stream’s forEach() method using Lambda expression · package net.bench.resources.stream.foreach.example; import java.util.Arrays; import java.util.List; public class StreamForEachLambdaExpression { public static void main(String[] args) { // create List of first 10 natural numbers List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); System.out.println("1.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
Java 8 Stream - filter() & forEach() - Examples Java Code Geeks - 2026
December 17, 2021 - It is a default method present ... interface in Java. Represented by the syntax – ... This method is used to refine the stream of elements based on a given condition....
🌐
GeeksforGeeks
geeksforgeeks.org › java › arraylist-foreach-method-in-java
ArrayList forEach() Method in Java - GeeksforGeeks
July 20, 2026 - Explanation: In the above example, we use the forEach() method with a lambda expression and conditional logic to filter and print elements based on a condition.
🌐
W3Schools
w3schools.com › java › java_foreach_loop.asp
Java For-Each Loop
The Java for-each loop steps through every element of an array or collection.
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java foreach()
Java forEach() with Examples - HowToDoInJava
February 6, 2023 - List<Integer> numberList = List.of(1,2,3,4,5); Consumer<Integer> action = System.out::println; numberList.stream() .filter(n -> n%2 != 0) .parallel() .forEachOrdered( action ); Program output. ... In this Java 8 tutorial, we learned to use the forEach() method for iterating though the items in Java Collections and/or Streams.