How to iterate a Java List using For Loop?

JavaObject Oriented ProgrammingProgramming

The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements. User of a list has quite precise control over where an element to be inserted in the List. These elements are accessible by their index and are searchable. ArrayList is the most popular implementation of the List interface.

You can utilize list.size() method to get the present size of the list and then for loop can be easily applied to iterate the list and use list.get(index) method to get the element.

for(int i= 0; i < list.size(); i++) {
   System.out.println(list.get(i));
}

Another important way is to use forEach loop which does not need size of the list prior to iterating the list.

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

Example 1

Following is the example showing for 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(int i= 0; i< list.size(); i++) {
         System.out.print(list.get(i) + " ");
      }
   }
}

Output

This will produce the following result −

1 2 3 4 5

Example 2

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
raja
Updated on 26-May-2022 13:20:10

Advertisements