How to Iterate LinkedList in Java?

07 Jan, 2021
LinkedList in java is basically a part of the collection framework present in java.util package. It is the implementation of the LinkedList data structure that stores elements in a non-contiguous manner inside the memory.
Five ways to iterate a LinkedList are:
Using for loopUsing while loopUsing enhanced for loopUsing IteratorUsing forEach() method
Using for loop
Using while loop
Using enhanced for loop
Using Iterator
Using forEach() method
Method 1: Using For Loop
Java
// Java program for iterating the LinkedList// using For loop  import java.util.LinkedList;  public class GFG {    public static void main(String[] args)    {          // Creating a LinkedList of Integer type        LinkedList<Integer> linkedList = new LinkedList<>();          // Inserting some Integer values to our LinkedList        linkedList.add(40);        linkedList.add(44);        linkedList.add(80);        linkedList.add(9);          // LinkedList after insertions: [40, 44, 80, 9]          // Calling the function to iterate our LinkedList        iterateUsingForLoop(linkedList);    }      // Function to iterate the LinkedList using a simple for    // loop    public static void             iterateUsingForLoop(LinkedList<Integer> linkedList)    {          System.out.print(            "Iterating the LinkedList using a simple for loop : ");          for (int i = 0; i < linkedList.size(); i++) {            System.out.print(linkedList.get(i) + " ");        }    }}
Iterating the LinkedList using a simple for loop : 40 44 80 9
Method 2: Using while Loop
We can iterate our LinkedList using a while loop in a very similar way as we did using a for loop.
Java
// Java program for iterating the LinkedList// using while loop  import java.util.LinkedList;  public class GFG {    public static void main(String[] args) {          // Creating a LinkedList of Character type        LinkedList<Character> vowels = new LinkedList<>();          // Inserting some Character values to our LinkedList        vowels.add('a');        vowels.add('e');        vowels.add('i');        vowels.add('o');        vowels.add('u');          // LinkedList after insertions: ['a', 'e', 'i', 'o', 'u']          // calling the function to iterate our LinkedList        iterateUsingWhileLoop(vowels);    }      // Function to iterate our LinkedList using while loop    public static void iterateUsingWhileLoop(LinkedList<Character> vowels){          System.out.print("Iterating the LinkedList using while loop : ");          int i=0;                while(i<vowels.size()){            System.out.print(vowels.get(i) + " ");            i++;        }      }}
Iterating the LinkedList using while loop : a e i o u
Method 3: Using enhanced for loop
Using enhanced for loop we can sequentially iterate a LinkedList. The execution of the enhanced for loop ends after we visit all the elements. Let us see an example of iterating the LinkedList using the enhanced for loop.
Java
// Java program for iterating the LinkedList// using Enhanced For loop  import java.util.LinkedList;  public class GFG {    public static void main(String[] args)    {          // Creating a LinkedList of String type        LinkedList<String> linkedList = new LinkedList<>();          // Inserting some String values to our LinkedList        linkedList.add("Geeks");        linkedList.add("for");        linkedList.add("Geeks");          // LinkedList after insertions: ["Geeks", "for",        // "Geeks]          // Calling the function to iterate our LinkedList        iterateUsingEnhancedForLoop(linkedList);    }      // Function to display LinkedList using Enhanced for    // loop    public static void iterateUsingEnhancedForLoop(LinkedList<String> linkedList)    {          System.out.print(            "Iterating the LinkedList using enhanced for loop : ");          for (String listElement : linkedList) {            System.out.print(listElement + " ");        }    }}
Iterating the LinkedList using enhanced for loop : Geeks for Geeks
Method 4: Using Iterator
To iterate the LinkedList using the iterator we first create an iterator to the current list and keep on printing the next element using the next() method until the next element exists inside the LinkedList.
We check if the LinkedList contains the next element using the hasNext() method.
Java
// Java program for iterating the LinkedList// using Iterator  import java.util.Iterator;  // Importing LinkedList class from// java.util packageimport java.util.LinkedList;  public class GFG {    public static void main(String[] args) {          // Creating a LinkedList of Integer Type        LinkedList<Integer> linkedList = new LinkedList<>();          // Inserting some Integer values to our LinkedList        linkedList.add(5);        linkedList.add(100);        linkedList.add(41);        linkedList.add(40);        linkedList.add(7);          // LinkedList after insertions : [5, 100, 41, 40, 7]          // Calling the function to iterate our LinkedList        iterateUsingIterator(linkedList);    }      // Function to iterate the Linked List using Iterator    public static void iterateUsingIterator(LinkedList<Integer> linkedList){          System.out.print("Iterating the LinkedList using Iterator : ");          // Creating an Iterator to our current LinkedList        Iterator it = linkedList.iterator();          // Inside the while loop we check if the next element        // exists or not if the next element exists then we print        // the next element and move to it otherwise we come out        // of the loop                // hasNext() method return boolean value          // It returns true when the next element          // exists otherwise returns false        while(it.hasNext()){              // next() return the next element in the iteration            System.out.print(it.next() + " ");        }      }}
Iterating the LinkedList using Iterator : 5 100 41 40 7
Method 5: Using forEach() method
forEach() method was introduced in Java8. 
It performs the specified task for each element of the Iterable until all elements have been processed or the action throws an exception. 
Syntax: 
public void forEach(Consumer<? super E> action)
Java
// Java program for iterating the LinkedList// using For Each loop  import java.util.LinkedList;  public class GFG {    public static void main(String[] args)    {          // Creating a LinkedList of Integer Type        LinkedList<Integer> linkedList = new LinkedList<>();          // Inserting some Integer values to our LinkedList        linkedList.add(1);        linkedList.add(2);        linkedList.add(3);        linkedList.add(4);        linkedList.add(5);          // LinkedList after insertions: [1, 2, 3, 4, 5]          // Calling the function to iterate our LinkedList        iterateUsingForEach(linkedList);    }      public static void            iterateUsingForEach(LinkedList<Integer> linkedList)    {          System.out.print(            "Iterating the LinkedList using for each function : ");          // Calling the forEach function to iterate through        // all the elements inside the Linked List        linkedList.forEach(            (element) -> System.out.print(element + " "));    }}
Iterating the LinkedList using for each function : 1 2 3 4 5
Java-Collections
java-LinkedList
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array