๐ŸŒ
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); } }
๐ŸŒ
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.โ€ ยท ...
Discussions

Java 8 Iterable.forEach() vs foreach loop - Stack Overflow
Regarding the performance issue - I guess it depends very much on the nature of the loop. In a project I'm working on, I have been using function-style loops similar to Iterable#forEach before Java 8 just because of the performance increase. The project in question has one main loop similar ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
.forEach() on a list vs .forEach() on a stream. What's the difference?
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
9
5
September 29, 2023
Which way it is thread-safe in Java Stream?
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 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. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar 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: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) 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/javahelp
8
2
August 22, 2021
๐ŸŒ
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.
๐ŸŒ
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. 1 3 5 ยท In this Java 8 tutorial, we learned to use the forEach() method for iterating though the items in Java Collections and/or Streams.
๐ŸŒ
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 - It takes a Consumer as an argument and applies that consumer's action to each element in the collection. A Consumer is a functional interface introduced in Java 8, located in the java.util.function package.
๐ŸŒ
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 ...
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ arraylist-foreach-method-in-java
ArrayList forEach() Method in Java - GeeksforGeeks
July 20, 2026 - Introduced in Java 8 as part of the Collections Framework enhancements. ... 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); } }
๐ŸŒ
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.
๐ŸŒ
Spring Framework Guru
springframework.guru โ€บ home โ€บ java 8 foreach
Java 8 forEach - Spring Framework Guru
May 20, 2019 - Internal iterator has been introduced in Java 8 with the introduction of Lambda expression. The forEach method of this post covers is an internal iterator. The code to iterate through the elements of a list using forEach is this.
๐ŸŒ
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 ...
๐ŸŒ
Javaprogramto
javaprogramto.com โ€บ 2019 โ€บ 07 โ€บ java-8-foreach.html
Java 8 forEach Examples on List, Set and Map
August 16, 2020 - But, the Separate forEach(BiConsumer biConsumer) method is implemented in the Map interface as the default method. This is invoked on any Map implementation such as HashMap, TreeHashMap, and LinkedHashMap. Example programs before and after java 8 on iterating ArrayList using forEach.
๐ŸŒ
Medium
neesri.medium.com โ€บ exploring-the-foreach-method-in-java-8-stream-api-3a871cdc07a0
Exploring the forEach Method in Java 8 Stream API | by A cup of JAVA coffee with NeeSri | Medium
July 20, 2025 - Here, the lambda expression updates the external variable sum, accumulating the sum of all numbers in the list. In addition to lambda expressions, forEach supports method references. Using method references can make the code more concise.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ stream-foreach-method-java-examples
Stream forEach() method in Java with examples - GeeksforGeeks
January 23, 2026 - import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); // Print each number in the list using forEach numbers.stream().forEach(System.out::print); } } ... Parameters: "action" a Consumer functional interface defining the operation to perform on each element. Return Value: None (void) - this is a terminal operation. Example 1: Print Each Element of a Reversely Sorted Integer Stream ... import java.util.*; class GFG { public static void main(String[] args) { List<Integer> list = Arrays.asList(2, 4, 6, 8, 10); // Sort in reverse order and print each element list.stream() .sorted(Comparator.reverseOrder()) .forEach(System.out::println); } }
๐ŸŒ
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)); } }
Top answer
1 of 8
654

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.

๐ŸŒ
Java Code Geeks
examples.javacodegeeks.com โ€บ home โ€บ java development โ€บ core java
For Each Loop Java 8 Example - Java Code Geeks
April 29, 2021 - From Java 8 and on, developers ... of this enhanced for loop. The new Stream class provides a forEach method, which can be used to loop over all of the selected elements of List, Set, and Map....
๐ŸŒ
Upgrad
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ java arraylist foreach
Java ArrayList forEach - upGrad
2 weeks ago - Here's an example that showcases the forEach() method in Java 8 and the forEachOrdered() method in Java Stream: In this example, we have a List called fruits containing different fruit names. First, we demonstrate the usage of the forEach() method available in Java 8.
๐ŸŒ
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.