How to iterate a Java List using For-Each Loop?

JavaObject Oriented ProgrammingProgramming

The List interface is a member of Java Collections Framework. It extends Collection and stores a sequence of elements. ArrayList and LinkedList are the most commonly used implementations of List interface. List provides user a precise control over where an element to be inserted in the List. These elements can be accessed by their index and are searchable.

A forEach loop iterate over the objects. As List contains objects, it can be easily iterated using forEach loop. List interface has forEach method as well which can be used to iterate the list. In this article, we'll explore both options with relevant examples.

forEach loop

for (Integer integer : list) {
   System.out.print(integer + " ");
}

List.forEach loop

list.forEach(i -> {System.out.print(i + " ");});

Example 1

Following is the example showing forEach loop to iterate the list −

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
     
      for (Integer integer : list) {
         System.out.print(integer + " ");
      }
   }
}

Output

This will produce the following result −

1 2 3 4 5

Example 2

Following is the example showing List.forEach loop to iterate the list −

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
      list.forEach(i -> {System.out.print(i + " ");});
   }
}

Output

This will produce the following result −

1 2 3 4 5
raja
Updated on 26-May-2022 13:20:39

Advertisements