Iterate through a LinkedList using an Iterator in Java

Java 8Object Oriented ProgrammingProgramming

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());
}
raja
Published on 18-Jan-2019 06:11:22
Advertisements