Iterate over ArrayList Using forEach Java

This example demonstrates how to iterate over ArrayList using forEach() method of ArrayList in Java.

Iterate over ArrayList in Java Example

The following example shows how to iterate over an ArrayList using
  • Java 8 forEach and lambda expression.
  • Simple for-each loop.
  • for loop with index.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class IterateOverArrayListExample {
    public static void main(String[] args) {
        List<String> tvShows = new ArrayList<>();
        tvShows.add("Breaking Bad");
        tvShows.add("Game Of Thrones");
        tvShows.add("Friends");
        tvShows.add("Prison break");

        System.out.println("=== Iterate using Java 8 forEach and lambda ===");
        tvShows.forEach(tvShow -> {
            System.out.println(tvShow);
        });        

        System.out.println("\n=== Iterate using simple for-each loop ===");
        for(String tvShow: tvShows) {
            System.out.println(tvShow);
        }

        System.out.println("\n=== Iterate using for loop with index ===");
        for(int i = 0; i < tvShows.size(); i++) {
            System.out.println(tvShows.get(i));
        }
    }
}

Output

=== Iterate using Java 8 forEach and lambda ===
Breaking Bad
Game Of Thrones
Friends
Prison break

=== Iterate using simple for-each loop ===
Breaking Bad
Game Of Thrones
Friends
Prison break

=== Iterate using for loop with index ===
Breaking Bad
Game Of Thrones
Friends
Prison break

Reference


Comments