- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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()); }
- Related Articles
- Iterate through a Collection using an Iterator in Java
- Iterate through elements of a LinkedList using a ListIterator in Java
- Iterate through a LinkedList in reverse direction using a ListIterator in Java
- Loop through a HashMap using an Iterator in Java
- Loop through an ArrayList using an Iterator in Java
- Iterate through an ArrayList using a ListIterator in Java
- How to iterate a Java List using Iterator?
- How to iterate List using Iterator in Java?
- Loop through the Vector elements using an Iterator in Java
- How many ways to iterate a LinkedList in Java?
- How an iterator object can be used to iterate a list in Java?
- Iterate through ArrayList in Java
- Iterate through Decade Tuple in Java
- Iterate through Ennead Tuple in Java
- Iterate through Octet Tuple in Java

Advertisements