- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
How to iterate over a Java list?
Often, you will want to cycle through the elements in a collection. For example, you might want to display each element.
The easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.
Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allow bidirectional traversal of a list and the modification of elements.
Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator() method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.
In general, to use an iterator to cycle through the contents of a collection, follow these steps −
- Obtain an iterator to the start of the collection by calling the collection's iterator() method.
- Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
- Within the loop, obtain each element by calling next().
Example
import java.util.ArrayList; import java.util.Iterator; public class IteratorSample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("JavaFx"); list.add("Java"); list.add("WebGL"); list.add("OpenCV"); Iterator iterator = list.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } } }
Output
JavaFx Java WebGL OpenCV
- Related Articles
- How to iterate over a list in Java?
- How to iterate over a C# list?
- Program to iterate over a List using Java 8 Lambda
- Iterate over a list in Python
- How to iterate a Java List?
- Java Program to Iterate over a HashMap
- Java Program to Iterate over a Set
- How to iterate a list in Java?
- Java Program to Iterate over enum
- How to iterate over a list of files with spaces in Linux?
- How to iterate through Java List?
- How to iterate a Java List using Iterator?
- Java Program to Iterate over an ArrayList
- How to iterate over a C# dictionary?
- How to iterate over a C# tuple?
