Adam Bien's Weblog

Java 8: From a for-loop to forEach statement

Ordinary for loops:

List<String> strings = new ArrayList<>();
for (String string : strings) {
	System.out.println("Content: " + string);

...can be easily translated into a forEach statement:

List<String> strings = new ArrayList<>(); -> {
	System.out.println("Content: " + string);

With the "functional looping style" any pre- or post-processing like filtering, grouping or even parallelization can be easily achieved:

        filter(s -> s.contains("java")).
        forEach((string) -> {
            System.out.println("Content: " + string);

NetBeans 8 converts ordinary for-loops into the functional notation by hitting the ALT+ENTER key on, or by clicking on the yellow bulb.

See you at Java EE Workshops at MUC Airport or on demand and in a location very near you:!

NEW dates, new workshop: Java EE 7 Workshops: Bootstrap, Effective, Architectures, JavaScript Bootstrap and HTML 5 December, 7th-11th
Online workshop: Java EE 7 Bootstrap


A book about rethinking Java EE Patterns


small correction: yellow bulb instead of yellow bulp

Posted by asdf on January 20, 2014 at 07:38 AM CET #

When talking about ordinary for loops, I still call them "new-style forma loops". I feel like an old guy :(

Posted by Danilo Piazzalunga on January 20, 2014 at 10:30 AM CET #

I still refer to ordinary for loops as "new-style for loops", and there already are newer-style loops. I'm looking forward to developing with Java 8 and NetBeans 8!

Posted by Danilo Piazzalunga on January 20, 2014 at 10:40 AM CET #

What actually is the benefit
For " -> {"
"for (String string : strings) {"

Posted by Wese on January 25, 2014 at 02:18 AM CET #

in the 'functional style loop' the iteration it's done by forEach statement and you'll focus only to the action of what to do on each element and you don't have to concentrate on how to go through collection, if if I'm not mistaken this function, forEach it's implemented on stream interface so it's applied to all collections.

Posted by sorin on September 19, 2014 at 03:28 PM CEST #

i want more detail about arraylist with custom objects

Posted by on July 08, 2015 at 02:00 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments