# 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();
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();
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