
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterate Through a LinkedList Using an Iterator in Java
An Iterator can be used to loop through an LinkedList. The method hasNext( ) returns true if there are more elements in LinkedList and false otherwise. The method next( ) returns the next element in the LinkedList and throws the exception NoSuchElementException if there is no next element.
A program that demonstrates this is given as follows.
Example
import java.util.LinkedList; import java.util.Iterator; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("John"); l.add("Sara"); l.add("Susan"); l.add("Betty"); l.add("Nathan"); System.out.println("The LinkedList elements are: "); for (Iterator i = l.iterator(); i.hasNext();) { System.out.println(i.next()); } } }
Output
The output of the above program is as follows −
The LinkedList elements are: John Sara Susan Betty Nathan
Now let us understand the above program.
The LinkedList is created and LinkedList.add() is used to add the elements to the LinkedList. Then the LinkedList elements are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows
LinkedList<String> l = new LinkedList<String>(); l.add("John"); l.add("Sara"); l.add("Susan"); l.add("Betty"); l.add("Nathan"); System.out.println("The LinkedList elements are: "); for (Iterator i = l.iterator(); i.hasNext();) { System.out.println(i.next()); }
Advertisements