Java 8 Features – ForEach Method

ForEach concept is included in Java version 8 i.e. it is available from Java 8 onwards. ForEach is included in Java for performing the clean iteration of Java Collections and Arrays. It also supports Generics.

ForEach for Java Collections

Using ForEach Java Collections can be iterated cleanly.

Example 1 –

Java Code using for-each loop –

package com.thinkconstructive;

import java.util.ArrayList;
import java.util.List;

public class DemoForEach {
    public static void main(String args[])
    {
        List<String> names = new ArrayList();
        names.add("Java8");
        names.add("Java9");
        names.add("Java10");
        names.add("Java11");
        names.add("Java12");

        for(String name: names)
        {
            System.out.println(name);
        }
    }
}

Output –

Java8
Java9
Java10
Java11
Java12

Above example explains that ArrayList contents can be iterated using for-each loop method and code becomes concise and clean.

Example 2 –

Java Code using forEach Lambda Expression –

package com.thinkconstructive;

import java.util.ArrayList;
import java.util.List;

public class DemoForEach {
    public static void main(String args[])
    {
        List<String> names = new ArrayList();
        names.add("Name1");
        names.add("Name2");
        names.add("Name3");
        names.add("Name4");
        names.add("Name5");
        
        names.forEach((name) -> System.out.println(name) );
    }
}

Output –

Name1
Name2
Name3
Name4
Name5

In the above example, for names ArrayList, forEach is used in combination with Lambda expression and all names stored in the given ArrayList got printed.

ForEach for Java Arrays

Using ForEach Java Arrays can be iterated cleanly.

Example 1 –

Java Code –

package com.thinkconstructive;

import java.util.ArrayList;
import java.util.List;

public class DemoForEach {
    public static void main(String args[])
    {
        int[] numArray = {1,2,3,4,5};
        int sumOfNumbers = 0;

        for(int value : numArray)
        {
            System.out.println(value);
            sumOfNumbers = sumOfNumbers + value;
        }

        System.out.println(sumOfNumbers);
    }
}

Output –

1
2
3
4
5
15

In the above example, numArray which is an Array of Integers is lopped withe the help of for-each loop as internally and respective numbers got printed. Additionally, sum of all numbers present in the array is calculated and printed.

What is NOT supported by Java forEach ?

  1. for-each loop does not support filtering such as removing element from collection.
  2. While traversing; replacing elements in an array or in a list is not supported
  3. Looping through multiple collections in parallel is not supported.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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