Instead of using a forEach just use streams from the beginning:

List<PersonWrapper> wrapperList = jrList.stream()
    .flatMap(jr -> seniorList.stream()
         .filter(sr -> jr.getName().equals(sr.getName()))
         .map(sr -> new PersonWrapper(jr, sr))
    )
    .collect(Collectors.toList());

By using flatMap you can flatten a stream of streams (Stream<Stream<PersonWrapper>>) into a single stream (Stream<PersonWrapper>)

If you can't instantiate wrapperList by yourself or really need to append to it. You can alter above snippet to following:

List<PersonWrapper> wrapperList = new ArrayList<>();

jrList.stream()
    .flatMap(jr -> seniorList.stream()
         .filter(sr -> jr.getName().equals(sr.getName()))
         .map(sr -> new PersonWrapper(jr, sr))
    )
    .forEach(wrapperList::add);
Answer from Lino on Stack Overflow
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java8 โ€บ java 8 foreach examples
Java 8 forEach examples - Mkyong.com
December 4, 2020 - 4.1 The forEach is not just for printing, and this example shows how to use forEach method to loop a list of objects and write it to files. ... 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> f
๐ŸŒ
ZetCode
zetcode.com โ€บ java โ€บ foreach
Java forEach - forEach on Java lists, maps, sets
June 17, 2025 - The forEach method executes a specified action for each element within an Iterable object, continuing until all elements are processed or an exception occurs. Introduced in Java 8, this method offers developers a modern, concise alternative to traditional looping constructs, simplifying the ...
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ core java โ€บ guide to the java foreach loop
Guide to the Java forEach Loop | Baeldung
June 17, 2025 - 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.โ€ ยท ...
๐ŸŒ
CodeAhoy
codeahoy.com โ€บ java โ€บ foreach-in-java
Complete Guide to Java 8 forEach | CodeAhoy
February 19, 2021 - Java 8 introduced a new concise and powerful way of iterating over collections: the forEach() method. While this method is the focus of this post, before we dive into it, weโ€™ll explore its cousin, the for-each loop to illustrate differences and similarities that weโ€™ll explore later.
๐ŸŒ
Medium
neesri.medium.com โ€บ master-in-java-8-foreach-48ac3fc940dc
Master in the forEach() Method in Java 8 | by A cup of JAVA coffee with NeeSri | Medium
August 3, 2024 - Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); // Java 8 forEach map.forEach((key, value) -> System.out.println(key + " -> " + value)); // Java 7 loop for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } List<String> list = Arrays.asList("apple", "banana", "orange"); // Java 8 forEach list.forEach(item -> System.out.println(item)); // Java 7 loop for (String item : list) { System.out.println(item); }
Top answer
1 of 3
12

Instead of using a forEach just use streams from the beginning:

List<PersonWrapper> wrapperList = jrList.stream()
    .flatMap(jr -> seniorList.stream()
         .filter(sr -> jr.getName().equals(sr.getName()))
         .map(sr -> new PersonWrapper(jr, sr))
    )
    .collect(Collectors.toList());

By using flatMap you can flatten a stream of streams (Stream<Stream<PersonWrapper>>) into a single stream (Stream<PersonWrapper>)

If you can't instantiate wrapperList by yourself or really need to append to it. You can alter above snippet to following:

List<PersonWrapper> wrapperList = new ArrayList<>();

jrList.stream()
    .flatMap(jr -> seniorList.stream()
         .filter(sr -> jr.getName().equals(sr.getName()))
         .map(sr -> new PersonWrapper(jr, sr))
    )
    .forEach(wrapperList::add);
2 of 3
4

While Lino's answer is certainly correct. I would argue that if a given person object in jrList can only ever have one corresponding match in seniorList maximum, in other words, if it's a 1-1 relationship then you can improve upon the solution given by Lino by finding the first match as follows:

List<PersonWrapper> resultSet = jrList.stream()
                .map(p -> seniorList.stream()
                        .filter(sr -> p.getName().equals(sr.getName()))
                        .findFirst()
                        .map(q -> new PersonWrapper(p, q))
                        .get())
                .collect(Collectors.toList());

or if there is no guarantee that each person in jrList will have a corresponding match in seniorList then change the above query to:

List<PersonWrapper> resultSet = jrList.stream()
                .map(p -> seniorList.stream()
                        .filter(sr -> p.getName().equals(sr.getName()))
                        .findFirst()
                        .map(q -> new PersonWrapper(p, q))
                        .orElse(null))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

The difference is that now instead of calling get() on the result of findFirst() we provide a default with orElse in case findFirst cannot find the corresponding value and then we filter the null values out in the subsequent intermediate operation as they are not needed.

๐ŸŒ
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.
Top answer
1 of 8
653

The better practice is to use for-each. Besides violating the Keep It Simple, Stupid principle, the new-fangled forEach() has at least the following deficiencies:

  • Can't use non-final variables. So, code like the following can't be turned into a forEach lambda:
Object prev = null;
for(Object curr : list)
{
    if( prev != null )
        foo(prev, curr);
    prev = curr;
}
  • Can't handle checked exceptions. Lambdas aren't actually forbidden from throwing checked exceptions, but common functional interfaces like Consumer don't declare any. Therefore, any code that throws checked exceptions must wrap them in try-catch or Throwables.propagate(). But even if you do that, it's not always clear what happens to the thrown exception. It could get swallowed somewhere in the guts of forEach()

  • Limited flow-control. A return in a lambda equals a continue in a for-each, but there is no equivalent to a break. It's also difficult to do things like return values, short circuit, or set flags (which would have alleviated things a bit, if it wasn't a violation of the no non-final variables rule). "This is not just an optimization, but critical when you consider that some sequences (like reading the lines in a file) may have side-effects, or you may have an infinite sequence."

  • Might execute in parallel, which is a horrible, horrible thing for all but the 0.1% of your code that needs to be optimized. Any parallel code has to be thought through (even if it doesn't use locks, volatiles, and other particularly nasty aspects of traditional multi-threaded execution). Any bug will be tough to find.

  • Might hurt performance, because the JIT can't optimize forEach()+lambda to the same extent as plain loops, especially now that lambdas are new. By "optimization" I do not mean the overhead of calling lambdas (which is small), but to the sophisticated analysis and transformation that the modern JIT compiler performs on running code.

  • If you do need parallelism, it is probably much faster and not much more difficult to use an ExecutorService. Streams are both automagical (read: don't know much about your problem) and use a specialized (read: inefficient for the general case) parallelization strategy (fork-join recursive decomposition).

  • Makes debugging more confusing, because of the nested call hierarchy and, god forbid, parallel execution. The debugger may have issues displaying variables from the surrounding code, and things like step-through may not work as expected.

  • Streams in general are more difficult to code, read, and debug. Actually, this is true of complex "fluent" APIs in general. The combination of complex single statements, heavy use of generics, and lack of intermediate variables conspire to produce confusing error messages and frustrate debugging. Instead of "this method doesn't have an overload for type X" you get an error message closer to "somewhere you messed up the types, but we don't know where or how." Similarly, you can't step through and examine things in a debugger as easily as when the code is broken into multiple statements, and intermediate values are saved to variables. Finally, reading the code and understanding the types and behavior at each stage of execution may be non-trivial.

  • Sticks out like a sore thumb. The Java language already has the for-each statement. Why replace it with a function call? Why encourage hiding side-effects somewhere in expressions? Why encourage unwieldy one-liners? Mixing regular for-each and new forEach willy-nilly is bad style. Code should speak in idioms (patterns that are quick to comprehend due to their repetition), and the fewer idioms are used the clearer the code is and less time is spent deciding which idiom to use (a big time-drain for perfectionists like myself!).

As you can see, I'm not a big fan of the forEach() except in cases when it makes sense.

Particularly offensive to me is the fact that Stream does not implement Iterable (despite actually having method iterator) and cannot be used in a for-each, only with a forEach(). I recommend casting Streams into Iterables with (Iterable<T>)stream::iterator. A better alternative is to use StreamEx which fixes a number of Stream API problems, including implementing Iterable.

That said, forEach() is useful for the following:

  • Atomically iterating over a synchronized list. Prior to this, a list generated with Collections.synchronizedList() was atomic with respect to things like get or set, but was not thread-safe when iterating.

  • Parallel execution (using an appropriate parallel stream). This saves you a few lines of code vs using an ExecutorService, if your problem matches the performance assumptions built into Streams and Spliterators.

  • Specific containers which, like the synchronized list, benefit from being in control of iteration (although this is largely theoretical unless people can bring up more examples)

  • Calling a single function more cleanly by using forEach() and a method reference argument (ie, list.forEach (obj::someMethod)). However, keep in mind the points on checked exceptions, more difficult debugging, and reducing the number of idioms you use when writing code.

Articles I used for reference:

  • Everything about Java 8
  • Iteration Inside and Out (as pointed out by another poster)

EDIT: Looks like some of the original proposals for lambdas (such as http://www.javac.info/closures-v06a.html Google Cache) solved some of the issues I mentioned (while adding their own complications, of course).

2 of 8
174

The advantage comes into account when the operations can be executed in parallel. (See http://java.dzone.com/articles/devoxx-2012-java-8-lambda-and - the section about internal and external iteration)

  • The main advantage from my point of view is that the implementation of what is to be done within the loop can be defined without having to decide if it will be executed in parallel or sequential

  • If you want your loop to be executed in parallel you could simply write

     joins.parallelStream().forEach(join -> mIrc.join(mSession, join));
    

    You will have to write some extra code for thread handling etc.

Note: For my answer I assumed joins implementing the java.util.Stream interface. If joins implements only the java.util.Iterable interface this is no longer true.

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
The new Stream class provides a forEach() method, which can be used to loop over all or selected elements of the list and map. The forEach() method provides several advantages over the traditional for loop e.g.
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2015 โ€บ 09 โ€บ java-8-foreach-loop-example.html
Java 8 forEach() Loop Example
Java 8 has introduced a new way to loop over a List or Collection, by using the forEach() method of the new Stream class. You can iterate over any Collection like List, Set, or Map by converting them into a java.util.sttream.Stream instance ...
๐ŸŒ
Java Guides
javaguides.net โ€บ 2019 โ€บ 11 โ€บ java-8-foreach-with-list-set-and-map.html
Java 8 forEach with List, Set and Map Examples
September 14, 2020 - Java 8 provides a new method forEach() to iterate the elements. It is defined in the Iterable and Stream interface. It is a default method defined in the Iterable interface. Collection classes that extend Iterable interface can use the forEach() ...
๐ŸŒ
BeginnersBook
beginnersbook.com โ€บ 2017 โ€บ 10 โ€บ java-8-foreach
Java 8 forEach method with example
import java.util.List; import java.util.ArrayList; public class Example { public static void main(String[] args) { List<String> names = new ArrayList<String>(); names.add("Maggie"); names.add("Michonne"); names.add("Rick"); names.add("Merle"); names.add("Governor"); names.stream() //creating stream .filter(f->f.startsWith("M")) //filtering names that starts with M .forEach(System.out::println); //displaying the stream using forEach } } ... For sequential streams the order of elements is same as the order in the source, so the output would be same whether you use forEach or forEachOrdered.
๐ŸŒ
Java Guides
javaguides.net โ€บ 2018 โ€บ 06 โ€บ guide-to-java-8-foreach-method.html
Java 8 forEach
September 5, 2024 - The following example demonstrates how to use forEach() to map a list of Entity objects to EntityDTO objects. import java.util.ArrayList; import java.util.Date; import java.util.List; public class ForEachRealTimeExamples { public static void main(String[] args) { List<Entity> entities = getEntities(); List<EntityDTO> dtos = new ArrayList<>(); // Mapping Entity to EntityDTO using forEach() entities.forEach(entity -> { dtos.add(new EntityDTO(entity.getId(), entity.getEntityName())); }); // Displaying EntityDTO details dtos.forEach(e -> { System.out.println(e.getId()); System.out.println(e.getEnt
๐ŸŒ
Javatpoint
javatpoint.com โ€บ java-8-foreach
Java 8 forEach() Method
Java 8 forEach Tutorial with examples and topics on functional interface, anonymous class, lambda for list, lambda for comparable, default methods, method reference, java date and time, java nashorn, java optional, stream, filter etc.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ java-8-foreach
Java 8 forEach
Java 8 provides the updated forEach() method with the ability to iterate the elements of a collection.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ arraylist-foreach-method-in-java
ArrayList forEach() Method in Java - GeeksforGeeks
July 11, 2025 - Example 1: Here, we will use the forEach() method to print all elements of an ArrayList of Strings. ... // Java program to demonstrate the use of forEach() // with an ArrayList of Strings import java.util.ArrayList; public class GFG { public static void main(String[] args) { // Create an ArrayList of Strings ArrayList<String> s = new ArrayList<>(); s.add("Cherry"); s.add("Blueberry"); s.add("Strawberry"); // Use forEach() to print each fruit s.forEach(System.out::println); } }
๐ŸŒ
Spring Framework Guru
springframework.guru โ€บ home โ€บ java 8 foreach
Java 8 forEach - Spring Framework Guru
May 20, 2019 - With both the new forEach method and the Java 8 Stream API, you can create a stream of elements in a collection and then pipeline the stream to a forEach method for iteration. The code to iterate through a stream of elements in a List is this.
๐ŸŒ
Studytonight
studytonight.com โ€บ java-8 โ€บ java-8-foreach
https://www.studytonight.com/java-8/java-8-foreach
import java.util.ArrayList; import java.util.List; public class STDemo { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("India"); list.add("China"); list.add("US"); list.add("UK"); list.forEach(System.out::println); } } ... The forEach() is primarily used to operate over the streams due to its functional nature. Here we have an integer array and then we get stream object of it to traverse its elements using forEach() method. import java.util.Arrays; import java.util.stream.IntStream; public class STDemo { public static void main(String[] args) { int[] arr = {2,5,36,9,8}; IntStream vals = Arrays.stream(arr); vals.forEach(elements->System.out.println(elements)); } }