Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic


How to loop ArrayList in Java


Earlier we shared ArrayList example and how to initialize ArrayList in Java. In this post we are sharing how to iterate (loop) ArrayList in Java.

There are four ways to loop ArrayList:

For Loop
Advanced for loop
While Loop
Iterator
Lets have a look at the below example ‚Äď I have used all of the mentioned methods for iterating list.

import java.util.*;
public class LoopExample {
   public static void main(String[] args) {

      ArrayList arrlist = new ArrayList();
      arrlist.add(14);
      arrlist.add(7);
      arrlist.add(39);
      arrlist.add(40);

      /* For Loop for iterating ArrayList */
      System.out.println("For Loop");
      for (int counter = 0; counter < arrlist.size(); counter++) {               
          System.out.println(arrlist.get(counter));         
      }           

      /* Advanced For Loop*/         
      System.out.println("Advanced For Loop");         
      for (Integer num : arrlist) {               
           System.out.println(num);         
      }

      /* While Loop for iterating ArrayList*/         
      System.out.println("While Loop");         
      int count = 0;         
      while (arrlist.size() > count) {
     System.out.println(arrlist.get(count));
         count++;
      }

      /*Looping Array List using Iterator*/
      System.out.println("Iterator");
      Iterator iter = arrlist.iterator();
      while (iter.hasNext()) {
         System.out.println(iter.next());
      }
   }
}
Output:

For Loop
14
7
39
40
Advanced For Loop
14
7
39
40
While Loop
14
7
39
40
Iterator
14
7
39
40
In the comment section below, Govardhan asked a question: He asked, how to iterate an ArrayList using Enumeration. Govardhan here is the code:

How to iterate arraylist elements using Enumeration interface

import java.util.Enumeration;
import java.util.ArrayList;
import java.util.Collections;
 
public class EnumExample {
 
   public static void main(String[] args) {
      //create an ArrayList object
      ArrayList arrayList = new ArrayList();
 
      //Add elements to ArrayList
      arrayList.add("C");
      arrayList.add("C++");
      arrayList.add("Java");
      arrayList.add("DotNet");
      arrayList.add("Perl");
 
      // Get the Enumeration object
      Enumeration e = Collections.enumeration(arrayList);
 
      // Enumerate through the ArrayList elements
      System.out.println("ArrayList elements: ");
      while(e.hasMoreElements())
      System.out.println(e.nextElement());
   }
}
Output:

ArrayList elements:
C
C++
Java
DotNet
Perl

asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes
43 views



Related Hot Questions



Walkin Jobs Opening



Government Jobs Opening


...