- 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
Iterating over ArrayLists in Java
Iterator in Java is used to traverse each and every element in the collection. Using it, traverse, obtain each element or you can even remove elements from ArrList. To use an iterator to cycle through the contents of a collection, at first obtain an iterator to the start of the collection by calling the collection's iterator( ) method. After that, set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. At last, within the loop, obtain each element by calling next( ).
Example
Let us now see an example to iterate over ArrayList −
import java.util.*; public class Main { public static void main(String args[]) { ArrayList myList = new ArrayList(); myList.add("Jack"); myList.add("Nathan"); myList.add("Tom"); myList.add("Ryan"); myList.add("David"); myList.add("Kevin"); myList.add("Steve"); myList.add("Nathan"); myList.add("Tim"); System.out.print("Values
"); Iterator i = myList.iterator(); while(i.hasNext()) { Object obj = i.next(); System.out.print(obj + " "); } System.out.println(); } }
Output
Values Jack Nathan Tom Ryan David Kevin Steve Nathan Tim
Example
Let us now iterate over ArrayList using for Each method −
import java.util.*; public class Main { public static void main(String args[]) { ArrayList myList = new ArrayList(); myList.add("Jack"); myList.add("Nathan"); myList.add("Tom"); myList.add("Ryan"); myList.add("David"); myList.add("Kevin"); myList.add("Steve"); myList.add("Nathan"); myList.add("Tim"); System.out.print("Values...
"); myList.forEach(number->System.out.println(number)); System.out.println(); } }
Output
Values... Jack Nathan Tom Ryan David Kevin Steve Nathan Tim
- Related Articles
- Iterating over Arrays in Java
- Iterating over array in Java
- The Iterating over Arrays in Java
- Iterating over Enum Values in Java
- How do you use ‘foreach’ loop for iterating over an array in C#?
- C++ Remove an Entry Using Key from HashMap while Iterating Over It
- C++ Remove an Entry Using Value from HashMap while Iterating over It
- How to avoid ConcurrentModificationException while iterating a collection in java?
- Iterating through a dictionary in Swift
- Iterating C# StringBuilder in a foreach loop
- Get Enumeration over HashSet in Java
- Delete items from dictionary while iterating in Python
- Why Choose Java Over PHP?
- Iterate over the elements of HashSet in Java
- When to use LinkedList over ArrayList in Java

Advertisements