Iterate LinkedList using forEach() Method Example

Java LinkedList Examples


In this example, we will see how to iterate over a Java LinkedList using forEach() method with an example.

Iterate or Loop Through Elements LinkedList in Java Example

package com.javaguides.collections.linkedlistexamples;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;

public class IterateOverLinkedListExample {
    public static void main(String[] args) {
        LinkedList < String > progLangs = new LinkedList < > ();

        progLangs.add("C");
        progLangs.add("C++");
        progLangs.add("Core Java");
        progLangs.add("Java EE");
        progLangs.add("Spring Framework");
        progLangs.add("Hibernate Framework");

        System.out.println("=== Iterate over a LinkedList using Java 8 forEach and lambda ===");
        progLangs.forEach(name - > {
            System.out.println(name);
        });

        System.out.println("\n=== Iterate over a LinkedList using simple for-each loop ===");
        for (String name: progLangs) {
            System.out.println(name);
        }
    }
}

Output

=== Iterate over a LinkedList using Java 8 forEach and lambda ===
C
C++
Core Java
Java EE
Spring Framework
Hibernate Framework

=== Iterate over a LinkedList using simple for-each loop ===
C
C++
Core Java
Java EE
Spring Framework
Hibernate Framework

Comments