Actually the enhanced for loop should look like this

for (final Room room : rooms) {
          // Here your room is available
}
Answer from ShyJ on Stack Overflow
🌐
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 { ...
🌐
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 ...
🌐
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)); } }
🌐
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.

Find elsewhere
🌐
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.
🌐
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.
🌐
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
🌐
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(","); } } }
🌐
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.
🌐
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
🌐
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)); } }
🌐
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.
🌐
Programiz
programiz.com › java-programming › library › arraylist › foreach
Java ArrayList forEach()
Become a certified Java programmer. Try Programiz PRO! ... The forEach() method performs the specified action on each element of the arraylist one by one.
🌐
Medium
rameshfadatare.medium.com › java-stream-foreach-examples-8696ed4af274
Java Stream forEach() Examples
September 27, 2024 - In this example, we use forEach() to update user records in a database. Assume we have a list of users, and we need to mark each of them as active: import java.util.stream.Stream; public class UpdateUserRecordsExample { static class User { String name; boolean active; User(String name) { this.name = name; this.active = false; // Initially inactive } void activate() { this.active = true; } @Override public String toString() { return name + " (Active: " + active + ")"; } } public static void main(String[] args) { Stream<User> users = Stream.of( new User("Alice"), new User("Bob"), new User("Charlie") ); // Use forEach() to activate each user users.forEach(user -> { user.activate(); System.out.println("User updated: " + user); }); } }
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.

🌐
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); } }