What you are looking for is called the map operation:

Thing[] functionedThings = Arrays.stream(things).map(thing -> functionWithReturn(thing)).toArray(Thing[]::new);

This method is used to map an object to another object; quoting the Javadoc, which says it better:

Returns a stream consisting of the results of applying the given function to the elements of this stream.

Note that the Stream is converted back to an array using the toArray(generator) method; the generator used is a function (it is actually a method reference here) returning a new Thing array.

Answer from Tunaki on Stack Overflow
🌐
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.” · And so, with forEach(), we can iterate over a collection and perform a given action on each element. For instance, let’s consider an enhanced for-loop version of iterating and printing a Collection of Strings: List names = List.of("Larry", "Steve", "James", "Conan", "Ellen"); for (String name : names) { LOG.info(name); }
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.

🌐
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 - action is an instance of the BiConsumer functional interface, which represents an operation that accepts two input arguments (key and value) and returns no result. 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); }
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java foreach()
Java forEach() with Examples - HowToDoInJava
February 6, 2023 - List<String> list = Arrays.asList("Alex", "Brian", "Charles"); list.forEach(System.out::println); Since Java 8, the forEach() has been added in the following classes or interfaces:
🌐
Java67
java67.com › 2016 › 01 › how-to-use-foreach-method-in-java-8-examples.html
10 Examples of forEach() method in Java 8 | Java67
In the years to come, you will ... a list or map, working with date and time, etc. If you need some help, you can also look at these free and comprehensive online Java courses which will not only teach you all this but much more. It's also the most up-to-date course, always updated to cover the latest Java versions like Java 11. For now, let's see a couple of examples of forEach() in Java 8...
🌐
Mkyong
mkyong.com › home › java8 › java 8 foreach examples
Java 8 forEach examples - Mkyong.com
December 4, 2020 - We can now reuse the same Consumer method and pass it to the forEach method of List and Stream. ... package com.mkyong.java8.misc; import java.util.*; import java.util.function.Consumer; import java.util.stream.Stream; public class ForEachConsumer { public static void main(String[] args) { List<String> list = Arrays.asList("abc", "java", "python"); Stream<String> stream = Stream.of("abc", "java", "python"); // convert a String to a Hex Consumer<String> printTextInHexConsumer = (String x) -> { StringBuilder sb = new StringBuilder(); for (char c : x.toCharArray()) { String hex = Integer.toHexString(c); sb.append(hex); } System.out.print(String.format("%n%-10s:%s", x, sb.toString())); }; // pass a Consumer list.forEach(printTextInHexConsumer); stream.forEach(printTextInHexConsumer); } }
🌐
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 ...
Find elsewhere
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.

🌐
CodingTechRoom
codingtechroom.com › question › get-return-list-from-foreach-java-8
How to Get a Return List from forEach in Java 8? - CodingTechRoom
... List<String> uppercaseNames = names.stream() .map(String::toUpperCase) .collect(Collectors.toList()); System.out.println(uppercaseNames); // Output: [ALICE, BOB, CHARLIE] The forEach method doesn't return a value, which means it can't be directly used to create a new collection.
🌐
TutorialsPoint
tutorialspoint.com › break-or-return-from-java-8-stream-foreach
Break or return from Java 8 stream forEach?
Read More: Java Stream API Improvements. The forEach method is a terminal operation, which runs action on each element of the stream. It?s meant to process each element; it doesn?t allow early exit by break or return. List names = Arrays.asList("Alice", "Bob", "Charlie"); names.stream().forEach(name -> { System.out.println(name); });
🌐
W3Docs
w3docs.com › java
Break or return from Java 8 stream forEach?
However, since forEach() is a terminal operation and is not intended to be used as a loop, it is generally better to use a different method such as findFirst() or anyMatch() if you only need to find a single element in the stream. Here's an example of how you can use findFirst() to find the first even number in a stream and return from the operation: List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Integer result = numbers.stream() .filter(n -> n % 2 == 0) .findFirst() .orElse(null); System.out.println(result); // prints 2
🌐
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)
Return Type: void (it does not return a value). Input: Accepts a Consumer<T> functional interface, which defines a single method void accept(T t). Here’s a simple example of forEach() iterating over a list and printing elements: import java.util.Arrays; import java.util.List; public class ForEachExample { public static void main(String[] args) { List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry"); // Print each fruit using forEach() fruits.forEach(fruit -> System.out.println(fruit)); } }
🌐
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 - Another subtle difference between the two forEach() methods is that Java explicitly allows modifying elements using the iterator. Streams, in contrast, should be non-interfering. Let’s look at removing and modifying elements in more detail. Let’s define an operation that removes the last element (“D”) of our list...
🌐
W3Schools
w3schools.com › java › ref_arraylist_foreach.asp
Java ArrayList forEach() Method
import java.util.ArrayList; public ... numbers.forEach( (n) -> { System.out.println(n); } ); } } ... The forEach() method performs an action on every item in a list....
🌐
Blogger
javarevisited.blogspot.com › 2015 › 09 › java-8-foreach-loop-example.html
Java 8 forEach() Loop Example
In the first example, we have a list of prime numbers and we want to print it using this new way of looping in Java 8: List<Integer> listOfPrimes = Arrays.asList(2, 3, 5, 7, 11, 3, 17); listOfPrimes.stream().forEach((i) -> { System.out.println(i); }); Here we are going through each element of the stream which is an Integer variable and passing it to System.out.println() for printing.
🌐
Codecademy
codecademy.com › docs › java › arraylist › .foreach()
Java | ArrayList | .forEach() | Codecademy
April 13, 2025 - The .forEach() method performs a specified action on each element of the ArrayList one by one. This method is part of the Java Collections Framework and was introduced in Java 8 as part of the Iterable interface, which ArrayList implements.
🌐
Studytonight
studytonight.com › java-8 › java-8-foreach
https://www.studytonight.com/java-8/java-8-foreach
In this example, we are iterating elements of the array list by using the forEach() method, and lambda expression is used to print elements. 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(country->System.out.println(country)); } }