Tuesday 20 January 2015

How to iterate or traverse ArrayList in Java


How to iterate or traverse ArrayList in Java


There are many ways to traverse over ArrayList.For ex: simple for loop,for-each loop and Iterator.

Lets have a look at the implementation of all different ways of traversing ArrayList.


1:  import java.util.ArrayList;  
2:  import java.util.Iterator;  
3:  /**  
4:   *   
5:   */  
6:  /**  
7:   * @author   
8:   *  
9:   */  
10:  public class ArrayListTraverseExample {  
11:       /**  
12:        * @param args  
13:        */  
14:       public static void main(String[] args) {  
15:      ArrayList<String> listCompanies = new ArrayList<String>();  
16:      listCompanies.add("Infosys");  
17:      listCompanies.add("TCS");  
18:      listCompanies.add("Cognizant");  
19:      listCompanies.add("Google");  
20:      System.out.println("Size of ArrayList : " + listCompanies.size());  
21:      System.out.println("\n*******Traversing ArrayList using for-each loop*******");  
22:      for(String company: listCompanies){  
23:        //print all elements from ArrayList one by one.  
24:        System.out.println("List of Companies are:"+company);  
25:      }  
26:      System.out.println("\n*******Traversing ArrayList using Iterator*******");  
27:      Iterator<String> itr = listCompanies.iterator();  
28:      while(itr.hasNext()){  
29:            System.out.println("List of Companies are:"+itr.next());  
30:      }  
31:      //You can also Loop over ArrayList using traditional for loop  
32:      System.out.println("\n*******Traversing ArrayList using simple for loop*******");  
33:      for(int i =0; i<listCompanies.size(); i++){  
34:          System.out.println("List of Companies are:"+listCompanies.get(i));  
35:      }  
36:       }  
37:  }  

Output:

Size of ArrayList : 4

*******Traversing ArrayList using for-each loop*******
List of Companies are:Infosys
List of Companies are:TCS
List of Companies are:Cognizant
List of Companies are:Google

*******Traversing ArrayList using Iterator*******
List of Companies are:Infosys
List of Companies are:TCS
List of Companies are:Cognizant
List of Companies are:Google

*******Traversing ArrayList using simple for loop*******
List of Companies are:Infosys
List of Companies are:TCS
List of Companies are:Cognizant
List of Companies are:Google




Please go through the program properly.Enjoy Reading.

No comments:

Post a Comment