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

Updated on: 25-Sep-2019

83 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements