How to Iterate Over Elements of Java LinkedList


In this example we will show how to iterate over elements of Java LinkedList using ListIterator’s next, hasNext, hasPrevious and previous methods.

Source Code

package com.beginner.examples;

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

public class IterateLinkedListUsingListIterator {

	public static void main(String[] args) {
		
		//create LinkedList.
		LinkedList linkedList = new LinkedList();
		
		linkedList.add("A");
		linkedList.add("B");
		linkedList.add("C");
		linkedList.add("D");
		
		/*
		 * To get an ListIterator object of LinkedList, use
                 * ListIterator listIterator() method.
		 */
		ListIterator itr = linkedList.listIterator();
		
		while(itr.hasNext()) {
			System.out.println(itr.next());
		}
	}
}

Output:

A
B
C
D

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments