Iterate through a LinkedList using an Iterator in Java


An Iterator can be used to loop through an LinkedList. The method hasNext( ) returns true if there are more elements in LinkedList and false otherwise. The method next( ) returns the next element in the LinkedList and throws the exception NoSuchElementException if there is no next element.

A program that demonstrates this is given as follows.

Example

 Live Demo

import java.util.LinkedList;
import java.util.Iterator;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("John");
      l.add("Sara");
      l.add("Susan");
      l.add("Betty");
      l.add("Nathan");
      System.out.println("The LinkedList elements are: ");
      for (Iterator i = l.iterator(); i.hasNext();) {
         System.out.println(i.next());
      }
   }
}

Output

The output of the above program is as follows −

The LinkedList elements are:
John
Sara
Susan
Betty
Nathan

Now let us understand the above program.

The LinkedList is created and LinkedList.add() is used to add the elements to the LinkedList. Then the LinkedList elements are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows

LinkedList<String> l = new LinkedList<String>();
l.add("John");
l.add("Sara");
l.add("Susan");
l.add("Betty");
l.add("Nathan");
System.out.println("The LinkedList elements are: ");
for (Iterator i = l.iterator(); i.hasNext();) {
   System.out.println(i.next());
}

Updated on: 29-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements