How to iterate a List using for Loop in Java?

JavaObject Oriented ProgrammingProgramming

The List interface extends the Collection interface and stores a sequence of elements. The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list. Unlike sets, the list allows duplicate elements and allows multiple null values if a null value is allowed in the list.

To use for loop, we need the size of the collection and indexed access to its item. The list has a size() method to give the size of the list and the get() method to get an item at a particular index. The following snippet shows how to iterate a list using for loop. In this example, we're discussing how to iterate a list using for loop using multiple examples.

Example - For loop

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

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<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
      for(int i= 0; i< list.size(); i++) {
         System.out.print(list.get(i) + " ");
      }
   }
}

Output

This will produce the following result −

A B C

Example 2

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

Output

This will produce the following result −

1 2 3
raja
Updated on 26-May-2022 13:21:31

Advertisements