🌐
W3Schools
w3schools.com › java › java_foreach_loop.asp
Java For-Each Loop
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... There is also a "for-each" loop, which is used exclusively to loop through elements in an array (or other data structures):
🌐
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 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:
Discussions

Java 8 Iterable.forEach() vs foreach loop - Stack Overflow
Once one gets used to the syntax of Iterable#forEach, it makes the code more readable, because you immediately get this additional information about the code. Traditional for-each loops will certainly stay good practice (to avoid the overused term "best practice") in Java. More on stackoverflow.com
🌐 stackoverflow.com
JS Array.foreach vs for-loops, pros and cons, which do you use and why

If you want to do sequential async tasks, you can't use forEach, you need to use a for loop with await.

More on reddit.com
🌐 r/webdev
27
8
February 21, 2022
What is the difference between map and forEach in Java streams in this case?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
12
2
June 2, 2024
What is difference between for and foreach, and which is better?
foreach is used for iterating over anything that implements IEnumerable - Lists, arrays, collections, etc. It performs the action once for each element and gives you a reference to the current item. for is a general purpose loop that uses an initialiser, iterator and condition for control. It doesn't need a list object. for (initializer; condition; iterator) Which one is better to use depends on your use case. If you want to perform an action for every element in an IEnumerable, use foreach. For example, I want to give each of my employees a 10% raise: foreach (var emplyee in myCompany.Employees) { employee.Salary += employee.Salary / 10; } Use for when you want to do something a set number of times, or need complex control over the flow, such as making numbers count backwards, do something for ever odd number, etc. for (int i = 0; i < 100; i++) { // Count from 0 to 99 } for (int j = 100; j > 0; j--) { // Count from 100 to 1 } for (int k = 0; k < 100; k += 5) { // Count from 0 to 100 in steps of 5 } More on reddit.com
🌐 r/csharp
14
3
September 13, 2019
🌐
GeeksforGeeks
geeksforgeeks.org › java › for-each-loop-in-java
For-Each Loop in Java - GeeksforGeeks
1 month ago - Example 2: Iterating in a List using for-each loop ... import java.util.*; class Geeks { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(3); list.add(5); list.add(7); list.add(9); int max = ...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › technotes › guides › language › foreach.html
The For-Each Loop
2 weeks ago - 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 construct:
🌐
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; ...
🌐
freeCodeCamp
freecodecamp.org › news › for-loop-in-java-foreach-loop-syntax-example
For Loop in Java + forEach Loop Syntax Example
February 7, 2022 - In the next example, we will use the for loop to print all the values of an array. int[] randomNumbers = {2, 5, 4, 7}; for (int i = 0; i < randomNumbers.length; i++) { System.out.println(randomNumbers[i]); } // 2 // 5 // 4 // 7 · This is almost ...
🌐
Programiz
programiz.com › java-programming › enhanced-for-loop
Java for-each Loop (With Examples)
In this tutorial, we will learn about the Java for each loop and its difference with for loop with the help of examples. The for-each loop is used to iterate each element of arrays or collections.
🌐
Codecademy
codecademy.com › docs › java › arraylist › .foreach()
Java | ArrayList | .forEach() | Codecademy
April 13, 2025 - This example demonstrates how to print all elements in an ArrayList using the .forEach() method with a lambda expression: ... The `.forEach()` method provides a more functional approach, accepting a lambda expression or method reference, while the enhanced for loop uses a more imperative style.
Find elsewhere
🌐
Zero To Mastery
zerotomastery.io › blog › enhanced-for-loop-java
How To Use Enhanced For Loops In Java (aka 'foreach') | Zero To Mastery
January 26, 2024 - In this example, the outer loop iterates over each row (which is itself an array), and the inner loop iterates over each element within that row. Alright, and that’s it. Let’s go over the most important points and wrap up.
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java foreach()
Java forEach() with Examples - HowToDoInJava
February 6, 2023 - So using the enhanced for-loop will give the same performance as forEach() method. default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } } The forEach() method performs the given action for each element of the List (or Set) until all elements have been processed or the action throws an exception. In the following example, System.out::println is a Consumer action representing an operation that accepts a single input argument and returns no result.
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.

🌐
GeeksforGeeks
geeksforgeeks.org › java › arraylist-foreach-method-in-java
ArrayList forEach() Method in Java - GeeksforGeeks
July 11, 2025 - In Java, the ArrayList.forEach() ... for each element in ArrayList. Example 1: Here, we will use the forEach() method to print all elements of an ArrayList of Strings....
🌐
CodeAhoy
codeahoy.com › java › foreach-in-java
Complete Guide to Java 8 forEach | CodeAhoy
February 19, 2021 - Let’s look at one example. In this example, we’ll iterate over a collection (List<String>) using both forEach() method and the for-each loop.
🌐
FavTutor
favtutor.com › blogs › foreach-java
For-Each Loop in Java (with Examples)
December 5, 2023 - In this example, the CustomIterable class implements the Iterable interface, providing an iterator through the CustomIterator inner class. Now, let's use our custom iterable object with the foreach loop: import java.util.Iterator; public class ForEachCustomObjectExample { public static void main(String[] args) { String[] projectNames = {"Project Alpha", "Project Beta", "Project Gamma", "Project Delta"}; CustomIterable customIterable = new CustomIterable(projectNames); System.out.println("Custom object iteration using foreach:"); for (String project : customIterable) { System.out.println("Worki
🌐
W3Schools
w3schools.com › java › ref_arraylist_foreach.asp
Java ArrayList forEach() Method
if else else if Short Hand If...Else Nested If Logical Operators Real-Life Examples Code Challenge Java Switch ... For Loop Nested Loops For-Each Loop Real-Life Examples Code Challenge Java Break/Continue Java Arrays
🌐
Mkyong
mkyong.com › home › java8 › java 8 foreach examples
Java 8 forEach examples - Mkyong.com
December 4, 2020 - Great examples. Thanks. ... It really helped me.. thank you so much ... Thanks, I was iterating a forEeah loop and instead of sysout. I want to perform few operations but I was getting an error. Your post help me identify what should I do. ... hello, thanks for this tutorial. In Java 8 possible to use ‘::’ ? items.forEach(System.out::println);
🌐
Runestone Academy
runestone.academy › ns › books › published › csjava › Unit7-Arrays › topic-7-3-arrays-with-foreach.html
7.3. Enhanced For-Loop (For-Each) for Arrays — CS Java
To set up a for-each loop, use for (type variable : arrayname) where the type is the type for elements in the array, and read it as “for each variable value in arrayname”. for (type item: array) { //statements using item; } See the examples below in Java that loop through an int and a String ...
🌐
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 - Since Java 8, the forEach() has been added in the following classes or interfaces: Iterable interface — This makes Iterable.forEach() method available to all collection classes except Map Map interface — This makes forEach() operation available to all map classes. Stream interface — This makes forEach() and forEachOrdered() operations available to all types of streams. Internally, the forEach() uses the enhanced for-loop for iterating through the collection items.
🌐
Java67
java67.com › 2016 › 01 › how-to-use-foreach-method-in-java-8-examples.html
10 Examples of forEach() method in Java 8 | Java67
You can read more about that in the Collections to Streams in Java 8 Using the Lambda Expressions course on Pluralsight, which provides an in-depth explanation of new Java 8 features. So far you have both basic and advanced examples of using the forEach() method, first with simply iterating over each element and then along with using the filter() method, Let's see one more example of the forEach() method along with the map() function, which is another key functionality of Stream API.
🌐
Runestone Academy
runestone.academy › ns › books › published › apcsareview › ArrayBasics › aForEach.html
8.2. Looping with the For-Each Loop — AP CSA Java Review - Obsolete
It will loop through the collection and each time through the loop it will use the next item from the collection. It starts with the first item in the array (the one at index 0) and continues through in order to the last item in the array. You can step through this code using the Java Visualizer ...