It doesn't matter which one you use, unless order is important. The forEach() will use the underlying's collection iterator, so if there's an order, then the elements will be processed accordingly. Stream.forEach() doesn't care about the order and thus can be different. Answer from nuttwerx on reddit.com
🌐
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); } }
🌐
W3Schools
w3schools.com › java › ref_arraylist_foreach.asp
Java ArrayList forEach() Method
Java Examples Java Videos Java ... Java Certificate · ❮ ArrayList Methods · Use a lambda expression in the ArrayList's forEach() method to print every item in the list: import java.util.ArrayList; public class Main { ...
Discussions

Foreach loop in java for a custom object list - Stack Overflow
I have an ArrayList for type Room (my custom object) Defined as below ArrayList rooms = new ArrayList (); After then adding a series of objects to the ArrayList I want to go More on stackoverflow.com
🌐 stackoverflow.com
use List Foreach instead of for() Java - Stack Overflow
I'm currently learning Java and I'm interested in learning how to use the list foreach method rather than using a manually constructed for loop. I suspect they can perform the same. My current code More on stackoverflow.com
🌐 stackoverflow.com
java - Usage of For-each loop vs functional operation vs Java8 streams - Software Engineering Stack Exchange
In the foreach style, each iteration ... inlined), just issuing a single virtual call to the acceptor object. My suspicion is that using forEach is faster. ... "With Java8 lambdas, you can only read locals, and only if they are declared final" -- this isn't true.... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
June 15, 2017
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
🌐
Tutorialspoint
tutorialspoint.com › java › java_foreach_loop.htm
Java - for each Loop
In this example, we're showing the use of a foreach loop to print contents of an List of String. Here we're creating an array of Strings as names and initialized it some values. Then using foreach loop, each name is printed. import java.util.Arrays; import java.util.List; public class Test { public static void main(String args[]) { List<String> names = Arrays.asList("James", "Larry", "Tom", "Lacy"); for( String name : names ) { System.out.print( name ); System.out.print(","); } } }
🌐
Baeldung
baeldung.com › home › java › core java › guide to the java foreach loop
Guide to the Java forEach Loop | Baeldung
June 17, 2025 - 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 ...
Find elsewhere
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › java-8-foreach
Java 8 forEach method with example
Inside forEach we are using a lambda expression to print each element of the list. import java.util.List; import java.util.ArrayList; public class Example { public static void main(String[] args) { List<String> fruits = new ArrayList<String>(); fruits.add("Apple"); fruits.add("Orange"); fruits.add("Banana"); fruits.add("Pear"); fruits.add("Mango"); //lambda expression in forEach Method fruits.forEach(str->System.out.println(str)); } }
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterate-through-list-in-java
Iterate through List in Java - GeeksforGeeks
July 23, 2025 - The processing order of stream().forEach() is undefined while in case of forEach(), it is defined. Both can be used to iterate over a List. ... // Java Program iterating over a List // using stream.forEach() method // Importing all classes of // java.util method import java.util.*; // Class class GFG { // Main driver method public static void main(String args[]) { // Creating an ArrayList List<String> myList = new ArrayList<String>(); // Adding elements to the List // Custom inputs myList.add("A"); myList.add("B"); myList.add("C"); myList.add("D"); // stream.forEach() method prints // all elements inside a List myList.stream().forEach( (temp) -> System.out.println(temp)); } }
🌐
Oracle
docs.oracle.com › javase › 8 › docs › technotes › guides › language › foreach.html
The For-Each Loop
2 weeks ago - The iterator is just clutter. Furthermore, it is an opportunity for error. The iterator variable occurs three times in each loop: that is two chances to get it wrong. The for-each construct gets rid of the clutter and the opportunity for error. Here is how the example looks with the for-each ...
Top answer
1 of 6
2

I think you can do it by iterating over the indexes of the cards:

IntStream.range(0, this.cards.size()).forEach(idx -> {
    DealOneCardToPlayer(
        this.table.players.get(idx % this.table.GetPlayerCount()),
        this.cards.get(idx));
});

Although this doesn't remove the cards as you go; if you really need this.cards to be empty after:

this.cards.clear();

If you want to limit the number of cards dealt out (e.g. you want to deal N cards to each player), the easiest way is to extract a sublist, and then just apply the same method above:

List<Card> cardsToDeal = this.cards.subList(0, numCardsToDeal);
IntStream.range(0, cardsToDeal.size()).forEach(idx -> {
    DealOneCardToPlayer(
        this.table.players.get(idx % this.table.GetPlayerCount()),
        cardsToDeal.get(idx));
});
cardsToDeal.clear();
2 of 6
1

You're talking about Java 8's Function API (and lambdas).

Essentially lambdas are a shorthand brethren to functions/methods, they have inputs and potentially return values. For the #forEach, it requests that you provide a function which accepts a T (Your list type), and returns nothing. This is known as a Consumer. The method then takes the Consumer you gave it, and calls it for each element on your list.

For equivalency, these are essentially the same thing as far as you're concerned when developing:

void someConsumerMethod(Card c) {
    //lambda code block
}


(Card c) -> //lambda code block


this::someConsumerMethod //direct reference to the first method

An example would be:

this.cards.forEach(c -> {
    System.out.println(c); //fully expanded
});
this.cards.forEach(c -> System.out.println(c)); //shorthand / one-liner
//or, since println already matches a Consumer<Object>, we can method reference it!
this.cards.forEach(System.out::println);

As for adapting your example, I wouldn't recommend modifying a collection while you iterate it (at least, not without using Iterator#remove). Andy Turner's answer already shows you how to use an application of IntStream to iterate the indexes you want.

🌐
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.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › ArrayList.html
ArrayList (Java Platform SE 8 )
2 weeks ago - Java™ Platform Standard Ed. 8 ... public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
🌐
IONOS
ionos.com › digital guide › websites › web development › java for-each loop
How to use for-each loops in Java - IONOS
November 3, 2023 - Not having to consider these aspects means you avoid the risk of an index being outside of the valid range. The for-each loop in­ter­nal­ly uses an iterator to call up each element of the array or list one by one.
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java arraylist › java arraylist foreach()
Java ArrayList forEach() with Examples - HowToDoInJava
January 12, 2023 - ArrayList forEach() method iterate the list and performs the argument action for each element of the list until all elements have been processed.
🌐
Baeldung
baeldung.com › home › java › java list › ways to iterate over a list in java
Ways to Iterate Over a List in Java | Baeldung
June 27, 2025 - ListIterator<String> listIterator = countries.listIterator(); while(listIterator.hasNext()) { System.out.println(listIterator.next()); } Since Java 8, we can use the forEach() method to iterate over the elements of a list.
🌐
W3Schools
w3schools.com › java › java_foreach_loop.asp
Java For-Each Loop
abs() acos() addExact() asin() atan() atan2() cbrt() ceil() copySign() cos() cosh() decrementExact() exp() expm1() floor() floorDiv() floorMod() getExponent() hypot() IEEEremainder() incrementExact() log() log10() log1p() max() min() multiplyExact() negateExact() nextAfter() nextDown() nextUp() pow() random() rint() round() scalb() signum() sin() sinh() sqrt() subtractExact() tan() tanh() toDegrees() toIntExact() toRadians() ulp() Java Output Methods ... add() addAll() clear() clone() contains ensureCapacity() forEach() get() indexOf() isEmpty() iterator() lastIndexOf() listIterator() remove() removeAll() removeIf() replaceAll() retainAll() set() size() sort() spliterator() subList() toArray() trimToSize() Java LinkedList Methods
🌐
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 - The forEach() method is part of the Iterable interface and is commonly used with collections (such as List, Set, etc.) and streams in Java…
🌐
Baeldung
baeldung.com › home › java › java collections › how to access an iteration counter in a for each loop
How to Access an Iteration Counter in a For Each Loop | Baeldung
January 8, 2024 - List rankings = new ArrayList<>(); movies.forEach(withCounter((i, movie) -> { String ranking = (i + 1) + ": " + movie; rankings.add(ranking); })); Inside the forEach is a call to the withCounter function to create an object which both tracks the count and acts as the Consumer that the forEach operation passes its values too. In this short article, we’ve looked at three ways to attach a counter to Java for each operation.
Top answer
1 of 1
3

Performance

In your example, I can hardly imagine any significant performance difference between the different styles, as in both cases, the work is done in N parallel Threads. Creating and managing the threads will vastly dominate the run time, even if the threads themself do nothing.

The different styles only apply in how you create the threads, start the threads, and wait for the threads to finish.

Similarities

Both styles have the basic way of iterating in common. Both the Java5 loop style and the (default implementation of the) Java8 lambda style use the iterator() of the array/list/collection and its next() and hasNext() methods.

Differences

What's different is the way the body gets executed.

The Java5 style loop immediately uses your code as the loop body (inside your parallelTestsExecution() method), while the Java8 lambda style encapsulates the functionality into the accept() method of an anonymous Acceptor object that gets called for each iteration. [Have a look at the class files created from your source. With the second style, there will be some xxx$1 and similar classes for the aforementioned Acceptors.]

So, there is an overhead when using the Java8 lambda style, but I guess the Hotspot compiler can optimize this to run as fast as a normal loop.

But this style affects the accessibility of local variables residing outside of the loop body. With Java5 loops, they are fully accessible, read and write, because they are in the same method. With Java8 lambdas, you can only read locals, and only if they are declared final [* see below] - your loop body resides in a different class, and accessing variables from your parallelTestsExecution() method is impossible for the JVM. The trick that the compiler uses, is to pass the value of your variable into the hidden constructor of the anonymous Acceptor class, and have the Acceptor class store this copy as an instance field. So, you can't transform your first loop to lambda style because you modify the "counter" variable inside which is impossible from an anonymous class.

It also affects debugging. Suppose you set a breakpoint at your line "thread.start();". In the first approach, you'll find yourself immediately in your parallelTestsExecution() method. With lambdas, you'll see an accept() method inside a forEach() method inside your parallelTestsExecution() method, maybe with some more intermediate glue.

[*] Remark on "final": As Jules correctly commented, the "final" declaration is no longer necessary. If you use a local variable inside of a lambda, it still has to be effectively final. That doesn't give you any more possibilities, just saves you typing the word "final".