Java 8 |How to use forEach

 199 total views,  1 views today

In this article let us see how to use forEach in Java 8.

forEach is one of the key features of Java 8.

Classic for-loop made developers write boiler-plate code and they have to handle iteration externally which are prone to errors.

But forEach handles the iterator internally and the developer can concentrate only on logic.

So, for-loop is an example of external iterator and forEach is an example if Internal iterator.

For instance,iterating a collection of String using for-loop,

//Iterate and print each element
for(String item:list) {
     System.out.println(item);
}

Using forEach,

//Iterate and print each element
list.forEach(item -> System.out.println(item));

See how simple the code is.Please note, we have used lambda expression.

Consider we need to write some logic inside the forEach. In such case,

list.forEach(item ->{
      if(item.equalsIgnoreCase("Item 1")) {
           System.out.println("I am Item 1");
       }
});

ForEach with static method reference

If we have a static method with an argument of the same type of Collection, then this static method can be called inside the forEach.

Let us define a class with a static method.

public class Test {

//Static method
static void print(String item) {
        System.out.println(item);
    }
}

This method can be invoked in forEach as below,

//Static Method reference
list.forEach(Test::print);

ForEach with Instance method reference

If we have an instance method with an argument of same type of Collection, then this instance method can be called inside the forEach.

Let us define a class and a method.

public class Test
{
    void apply(String item) {
        System.out.println(item);
    }
}

This method can be invoked in forEach as below,

//Create an instance and instance Method reference
Test test = new Test();
list.forEach(test::apply);

Please refer to Iterate a list using forEach and Iterate a map using forEach for more examples.

Please refer to External iterator vs internal iterators to know how forEach controls iteration.

Java 8 forEach official documentation.

These are the main usages of forEach and please be in touch with my blog for more updates om java 8 and various other tutorials.

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

2 thoughts on “Java 8 |How to use forEach

    • Author gravatar

      Wow that was odd. I just wrote an incredibly long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say excellent blog!

      • Author gravatar

        Ha Ha ..Sorry I used to get a lot of Spam comments so have to approve one by one. But I really got your comment.

        Thank you so much for your feedback and you have made my day! Please visit my LinkedIn we can connect over there!

        linkedin.com/in/rajasekar-sribalan-5b191b34

        Thank you buddy !Please keep following our site(www.staticreference.com) and spread a word about us via your social shares and references:)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.