How many ways to iterate a LinkedList in Java

In the earlier post we have discus linkedlist in java  , I Assuming you have gone through linkedlist in java and know about how to create linkedlist in java .In this tutorial we will discuss different ways of iterating linkedlist in java as following

  1. For loop
  2. Enhanced for loop
  3. While loop
  4. Iterator

Let’s try code for these method of iterating linkedlist in java

import java.util.Iterator;

import java.util.LinkedList;

public class LinklistIterator {

	public static void main(String[] args) {
		/*
		 * Constructs an empty list.
		 */
		LinkedList<String> linkedList = new LinkedList<String>();

		//adding element in linkedlist
		
		linkedList.add("PHP");
		linkedList.add("JAVA");
		linkedList.add("C++");
		linkedList.add("Android");
		
		System.out.println("===>> Iterate Linkedlist using for loop");
		//for loop
		for (int i = 0; i < linkedList.size() -1 ; i++) {
			System.out.println("element is ="+ linkedList.get(i));
		}
		
    System.out.println("===>> Iterate Linkedlist using Enhanced for loop");
		//Enhanced for loop
         for(String element : linkedList){
        	 System.out.println("element is ="+ element);
         }

       System.out.println("===>>Iterate Linkedlist using while loop");
		//While loop
       int i = 0;
       while (i < linkedList.size() -1 ) {
		   System.out.println("element is ="+ linkedList.get(i));
		      i++;
	     }
		System.out.println("===>> Iterate Linkedlist using Iterator");         
       //Iterator
		Iterator<String> itr = linkedList.iterator();
		while (itr.hasNext()) {
			System.out.println("element is =" + itr.next());

		}
		

	}

}

Output :

===>> Iterate Linkedlist using for loop
element is =PHP
element is =JAVA
element is =C++
===>> Iterate Linkedlist using Enhanced for loop
element is =PHP
element is =JAVA
element is =C++
element is =Android
===>>Iterate Linkedlist using while loop
element is =PHP
element is =JAVA
element is =C++
===>> Iterate Linkedlist using Iterator
element is =PHP
element is =JAVA
element is =C++
element is =Android

A Guide To LinkedList

Java Doc – LinkedList

 

Leave a Reply

Your email address will not be published. Required fields are marked *

90 − 88 =