In Java, LinkedList is a popular data structure that is an implementation of the List interface, meaning that it supports all the operations defined in the List interface, such as add, remove, and get.
We frequently use it to store and manipulate a large number of data elements. In Java, iterating over a LinkedList means traversing the elements of the list one by one. It is a common operation that is performed to traverse the elements of the list.
There are several ways to iterate over a LinkedList in Java, each with its own advantages and disadvantages. In this tutorial, we will understand the different ways to iterate over elements of LinkedList.
Before we go to learn different ways to iterate over a LinkedList, recommend that you first understand about what LinkedList is in simple words.
Now let’s explore the most common ways to iterate over a LinkedList. There are five ways in which LinkedList can be iterated in Java. They are as follows:
- For loop
- Advanced For loop
- While loop
- Iterator
- ListIterator
Iterating LinkedList using for loop
The simplest way to iterate over elements of LinkedList in Java is to use a for loop. In this method, we use the size() method provided by LinkedList to determine the number of elements in the list. Then, we will use a for loop to iterate over the elements.
Let’s take an example program where we will iterate LinkedList using for loop.
Program code 1:
package iterateLinkedList; import java.util.LinkedList; public class LinkedListEx1 { public static void main(String[] args) { // Create a generic LinkedList object of string type. LinkedList<String> list = new LinkedList<String>(); // an empty list. // Adding elements in the list. list.add("Red"); list.add("Yellow"); list.add("Green"); list.add("White"); // Iterating linked list using for loop. System.out.println("**For loop**"); for(int i = 0; i < list.size(); i++) { Object element = list.get(i); // Return type of get() method is an Object. System.out.println(element); } } }
Output: **For loop** Red Yellow Green White
The advantage of using a for loop to iterate over a LinkedList is that it is simple and easy to understand. However, the disadvantage of this method is that it is not very efficient for large data in the LinkedList because the size() method has to be called for every iteration.
Iterating over LinkedList using while loop
The second method to iterate over elements of linked list is to use while loop. It is efficient for a small amount of data in LinkedList. Let’s write a program for it.
Program code 2:
package iterateLinkedList; import java.util.LinkedList; public class LinkedListEx { public static void main(String[] args) { // Create a LinkedList object of string type. LinkedList cities = new LinkedList(); // Adding elements of only string type. cities.add("New York"); cities.add("Dhanbad"); cities.add("Sydney"); cities.add("London"); // Iterating over linked list using while loop. System.out.println("**While Loop**"); int num = 0; while(cities.size() > num) { System.out.println(cities.get(num)); num++; } } }
Output: **While Loop** New York Dhanbad Sydney London
Iterate LinkedList in Java using Advanced for loop
Another way to iterate over a LinkedList in Java is to use an advanced for loop or for-each loop. In this method, we use the advanced for loop to iterate over elements of the LinkedList directly.
Let’s take an example in which we will iterate over elements of linked list using for-each loop.
Program code 3:
package stringPrograms; import java.util.LinkedList; public class LinkedListEx { public static void main(String[] args) { // Create a LinkedList object of string type. LinkedList fruits = new LinkedList(); // Adding elements of only string type. fruits.add("Banana"); fruits.add("Mango"); fruits.add("Orange"); fruits.add("Apple"); // Iterating using advanced for loop. System.out.println("**Advanced For loop**"); for(String str: fruits) { System.out.println(str); } } }
Output: **Advanced For loop** Banana Mango Orange Apple
The major advantage of using an advanced for loop to iterate over a LinkedList in Java is that it is more efficient than using a for loop or while loop. This is because the size() method does not have to be called for every iteration. However, the disadvantage of this method is that it does not provide any access to the index of the current element.
How to iterate Java LinkedList using Iterator?
The most efficient way to iterate over elements of LinkedList in Java is to use an Iterator. In this method, we will use the iterator() method provided by iterable interface to create an Iterator object, which we will use to iterate over elements of LinkedList.
Let’s take an example program where we will iterate elements of the linked list using Iterator. Using Iterator, we will iterate the list in the forward direction only. Follow all the steps given in the following source code.
Program code 4:
package iterateLinkedList; import java.util.Iterator; import java.util.LinkedList; public class LinkedListEx2 { public static void main(String[] args) { // Create a generic LinkedList object of Character type. LinkedList<Character> list = new LinkedList<Character>(); // Adding elements in the list. list.add('A'); list.add('B'); list.add('C'); list.add('D'); list.add('E'); // Iterating using Iterator. System.out.println("**Using Iterator**"); Iterator<Character> itr = list.iterator(); while(itr.hasNext()) { Object obj = itr.next(); System.out.println(obj); } } }
Output: **Using Iterator** A B C D E
The advantage of using an Iterator to iterate over a LinkedList is that it does not require calling the size() method or accessing the elements directly.
In addition, the Iterator interface also provides methods for removing elements during the iteration. However, the disadvantage of this technique is that the length of code increases as compared to the previous methods.
How to traverse LinkedList in Java using ListIterator?
ListIterator is the most powerful iterator that allows us to traverse the LinkedList both forward and backward. The advantage of using ListIterator to traverse over a LinkedList in Java is that it offers additional methods for bidirectional iteration and modification of the list during iteration.
Let’s take an example program where we will traverse or iterate elements of LinkedList using ListIterator. We will iterate elements of list in both forward as well as backward directions. Look at the following source code to understand better.
Program code 5:
package iterateLinkedList; import java.util.LinkedList; import java.util.ListIterator; public class LinkedListEx3 { public static void main(String[] args) { // Create a generic LinkedList object of type Integer. LinkedList<Integer> list = new LinkedList<Integer>(); // Adding elements in the list. list.add(10); list.add(20); list.add(30); list.add(40); list.add(50); System.out.println("LinkedList original order"); System.out.println(list); ListIterator<Integer> litr = list.listIterator(); System.out.println("Interating in forward direction"); while(litr.hasNext()) { Object obj = litr.next(); System.out.println(obj); } System.out.println("Iterating in backwrd direction"); while(litr.hasPrevious()) { Object obj1 = litr.previous(); System.out.println(obj1); // This statement will throw Concurrent Modification Exception // because we cannot add or remove an element in the LinkedList during the iteration. list.add(60); } System.out.println(list); } }
Output: LinkedList original order [10, 20, 30, 40, 50] Interating in forward direction 10 20 30 40 50 Iterating in backwrd direction 50 java.util.ConcurrentModificationException
Best Practices for Iterating LinkedList in Java
While iterating over elements of LinkedList in Java, there are some key points that you should follow to ensure efficient and correct traversal of the list.
- Use an Iterator or ListIterator for efficient traversal of the list.
- Avoid using a for loop or while loop to iterate over a LinkedList because it is less efficient than using an Iterator or ListIterator.
- Use a for-each loop if you do not need access to the index of the current element.
- Use the remove() method of the Iterator or ListIterator to remove elements during the iteration.
- Avoid modifying the LinkedList during iteration because it can cause a ConcurrentModificationException.
In this tutorial, we have covered all the important points related to how to iterate LinkedList in Java with example programs. Hope that you will have understood the basic concepts of iterating LinkedList and practiced all programs.
Thanks for reading!!!
Next ⇒ Java Set Interface