forEach – Java 8 Feature

forEach - Java 8 Feature

0
1208

With many new features, Java 8 has has an addition of forEach as one of the most easy one to use. It reduces the coding time and speeds up the process of iteration as well.

Below example shows how to iterate a List in Java 8 using this new feature. We also need to note that Lambda expression gets used while using it. So if you have not understood the Lambda expressions yet, have a quick go through here.

Hello World forEach Iteration

package com.gb.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Java8ForEachLoop {

    public static void main(String[] args) {
    
     List<String> stringSet1 = new ArrayList<String>();
     stringSet1.add("Hello");
     stringSet1.add("World");
     stringSet1.add("ForEach ");
     stringSet1.add("Code");
    
     List<String> list = Arrays.asList("Hello", "World", "ForEach", "Code", "Sample");
    
     System.out.println("Printing Using Java 7 way :");
    
     for(String n: list) {
      System.out.println(n);
     }
    
     System.out.println("Now Printing Using Java 8 forEach way :");
    
     list.forEach(n -> System.out.println(n));
    }
}

The output comes as :

Printing Using Java 7 way :

Hello
World
forEach
Code
Sample
Now Printing Using Java 8 forEach way :
Hello
World
forEach
Code
Sample

This is fairly easy and common to use feature. This can be used to iterate the map’s content as well. So have you started using it yet? If not, what are you waiting for 🙂

References :

Java 8 Feature – JavaDoc

Previous articleLambda Expression – Java 8 Feature
Next articleWeakHashMap in Java with Code Sample
I have spent almost 10 years playing around Java and related technologies. I love to write on different topics and would be very much willing to hear back your feedback/suggestions on them. This site is a medium to share my knowledge with the Java folks and grow further. My other interests include traveling, driving, swimming and dance. But yes, my web site has become my passion over the time :) I live in Scotland and travel to India often, my roots being there.

NO COMMENTS

LEAVE A REPLY