The classic for loop gives you full control over iteration: you manage the index yourself, so you can start anywhere, end early, step by two, or go backwards. It is the right choice when you need the position of each element — for example, to compare adjacent items, to update specific indices, or to iterate only over a slice of the list. The loop runs from index 0 to list.size() - 1; accessing any index outside that range throws an IndexOutOfBoundsException.

public static void iterateUsingRegularForLoop() { List<String> groceries = List.of("Tomatoes", "Potato", "Eggplant","Broccoli", "Squash"); for(int i=0; i<groceries.size(); i++) { // regular for loop System.out.println("#Item : "+ groceries.get(i)); } }
public static void iterateUsingEnhancedForLoop() { List<String> groceries = List.of("Tomatoes", "Potato", "Eggplant","Broccoli", "Squash"); for (String item : groceries) { // enhanced for loop syntax System.out.println("#Item : " + item); } }
Iterator package io.cscode.collections.list.examples; import java.util.Iterator; import java.util.List; public class IterateThroughListUsingIterator { public static void iterateUsingIterator() { List<String> groceries = List.of("Tomatoes", "Potato", "Eggplant","Broccoli", "Squash"); //iterator works based on a pointer hasNext() will tell whether it reached end of List or not // and next() will fetch the element and move pointer to next element if there is any System.out.println("###### iterator in while loop #####"); Iterator<String> ite = groceries.iterator(); while(ite.hasNext()) { System.out.println("inside while loop : "+ ite.next()); } // same above logic can be implemented using while loop as well. System.out.println("###### iterator in for loop #####"); for(Iterator<String> it = groceries.iterator(); it.hasNext();) { System.out.println("inside for loop : "+ it.next()); } } public static void main(String[] args) { iterateUsingIterator(); } }

You can loop through elements of List using a while with a condition that checks whether we reach end of list or not. In below example we are using an integer counter to check end of loop.

public static void iterateUsingWhileLoop(){ List<String> groceries = List.of("Tomatoes", "Potato", "Eggplant","Broccoli", "Squash"); int counter =0; while(counter<groceries.size()) { System.out.println("#Item : " + groceries.get(counter++)); } }

Similar Articles

  1. How to remove elements from a List
  2. How to remove elements from a List while iterating