How to Browse a LinkedList in Java

In the previous tutorial,  We saw a class  LinkedList and its constructors and methods for example. In this tutorial, we'll see how to navigate through a LinkedList.

LinkedList can be processed with one of 4 loops:
  1. Loop for
  2. Loop for advanced or foreach
  3. Loop while
  4. Loop while+Iterator
Le The following code illustrates the 4 solutions mentioned to browse a LinkedList in java containing elements of type String:

import java.util.ArrayList; 
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;

public class parcours {

public static void main(String[] args) {

LinkedList< String> llist = new LinkedList< String> ();

llist.add("smartphone");
llist.add("tablet");
llist.add("phablet");

/*For Loop*/
System.out.println("For Loop");
for(int i = 0 ; i < llist.size(); i++)
System.out.println(llist.get(i));

/*Advanced For Loop*/
System.out.println("\nAdvanced For Loop");
for(String n: llist)
System.out.println(n);

/*Loop While*/
System.out.println("\nLoop while");
int i = 0;
while(i< llist.size()){
System.out.println(llist.get(i));
i++;
}

/*While + Iterator Loop*/
System.out.println("\nIterator Loop");
Iterator< String> it = llist.iterator();
while(it.hasNext())
System.out.println(it.next());

}
}
Output:

Loop for
smartphone
tablet
phablet

Advanced for loop
smartphone
tablet
phablet

Loop while< br />smartphone
tablet
phablet

Loop Iterator
smartphone
tablet
phablet
Iterator is obtained from the iterator() from LinkedList. You can iterate through the elements of iterator with the while loop that takes place as long as there are still elements. hasNext() returns true if there are elements to browse otherwise false. iterator.next() displays the following item in the LinkedList.

References:
How to Iterate through LinkedList Instance in Java?