In the last tutorial we discussed LinkedList and it’s methods with example. Here we will see how to loop/iterate a LinkedList. There are four ways in which a LinkedList
can be iterated –
- For loop
- Advanced For loop
- Iterator
- While Loop
Example:
In this example we have a LinkedList of String Type and we are looping through it using all the four mentioned methods.
package beginnersbook.com; import java.util.*; public class LinkedListExample { public static void main(String args[]) { /*LinkedList declaration*/ LinkedList<String> linkedlist=new LinkedList<String>(); linkedlist.add("Apple"); linkedlist.add("Orange"); linkedlist.add("Mango"); /*for loop*/ System.out.println("**For loop**"); for(int num=0; num<linkedlist.size(); num++) { System.out.println(linkedlist.get(num)); } /*Advanced for loop*/ System.out.println("**Advanced For loop**"); for(String str: linkedlist) { System.out.println(str); } /*Using Iterator*/ System.out.println("**Iterator**"); Iterator i = linkedlist.iterator(); while (i.hasNext()) { System.out.println(i.next()); } /* Using While Loop*/ System.out.println("**While Loop**"); int num = 0; while (linkedlist.size() > num) { System.out.println(linkedlist.get(num)); num++; } } }
Output:
**For loop** Apple Orange Mango **Advanced For loop** Apple Orange Mango **Iterator** Apple Orange Mango **While Loop** Apple Orange Mango
Leave a Reply