In this article we will discuss how to iterate over a LinkedList Collection in Java and access objects.

To fetch the Iterator from a LinkedList object use following member function,

ListIterator<E> listIterator();

It will return ListIterator object that implements Iterator that provides functions to iterate over the LinkedList object. It manages an internal Cursor which is equivalent to head reference of Linked List data structure. This function will make the cursor to point to the first element if available.

ListIterator provides following functions,

E next();

It will return the next element in the list and updates the internal cursor to points to next element.
boolean hasNext();

This function tells if there is any next element available or not.
E previous();

It will return the prev element in the list and updates the internal cursor to points to prev element.
boolean hasPrevious();

This function tells if there is any next element available or not.

There is also an overloaded version of listIterator() that will return the Iterator pointing to a specified index instead of start of LinkedList i.e.

ListIterator<E> listIterator(int index);

Lets checkout an example. Here we will iterate over the LinkedList object in forward direction,
package com.thispointer.java.collections.linkedlist;

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class Example3 {

	public static void main(String[] args) {

		// Create a LinkedList of String objects
		List<String> listOfStr = new LinkedList<>();
		
		// Add Elements at the end of LinkedList
		listOfStr.add("333");
		listOfStr.add("456");
		listOfStr.add("666");
		listOfStr.add("789");
		listOfStr.add("999");
		
		// Get ListIterator from List Object 
		// which points to 0th Position in List
		ListIterator<String> listIt = listOfStr.listIterator();
		
		System.out.println("Iterate List in forward Direction");
	
		// Iterate through LinkedList in forward direction
		while(listIt.hasNext())
		{
                        // Will return the element to which cursor points
                        // Also, increments the cursor to point to next location
			String temp = listIt.next();
			System.out.println(temp);
		}
		
		// Get ListIterator from List Object 
		// which points to 2nd Position in List
		listIt = listOfStr.listIterator(2);
		
		System.out.println("Start from 2nd Position : Iterate List in forward Direction");
	
		// Iterate through LinkedList in forward direction
		while(listIt.hasNext())
		{
			String temp = listIt.next();
			System.out.println(temp);
		}
	}
}

Output
Iterate List in forward Direction
333
456
666
789
999
Start from 2nd Position : Iterate List in forward Direction
666
789
999

So, this is how we can iterate over a LinkedList. In next article we will discuss how to iterate over a LinkedList in reverse direction.

 

Join a list of 2000+ Programmers for latest Tips & Tutorials