W3docs

How to print out all the elements of a List in Java?

To print out all the elements of a List in Java, you can use a for loop or an enhanced for loop.

To print out all the elements of a List in Java, you can use a for loop or an enhanced for loop.

Here's an example of how you can use a for loop to print out the elements of a List:


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

public class Main {
  public static void main(String[] args) {
    // Create a List
    List<String> list = new ArrayList<>();
    list.add("Apple");
    list.add("Banana");
    list.add("Carrot");

    // Print out the elements of the List
    for (int i = 0; i < list.size(); i++) {
      System.out.println(list.get(i));
    }
  }
}

This code will print out the following output:


Apple
Banana
Carrot

Here's an example of how you can use an enhanced for loop to print out the elements of a List:


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

public class Main {
  public static void main(String[] args) {
    // Create a List
    List<String> list = new ArrayList<>();
    list.add("Apple");
    list.add("Banana");
    list.add("Carrot");

    // Print out the elements of the List using an enhanced for loop
    for (String item : list) {
      System.out.println(item);
    }
  }
}

This produces the same output:


Apple
Banana
Carrot

Both approaches are valid, but the enhanced for loop is generally preferred for its simplicity and readability when iterating through collections.