Iterating ArrayLIst in java using for loop,while loop and Iterator

No comments
In this article we will learn different ways of iterating ArrayList in java.There are various ways of iterating ArrayList in java and we will discuss 4 different ways for iterating ArrayList.

  • Iterating ArrayList using while loop in java

  • Iterating ArrayList using for loop in java

  • Iterating ArrayList using advance for loop in java

  • Iterating ArrayList using Iterator in java

Different methods/functions used-
int size() -This method is used to get the number of elements in ArrayList.
boolean hasNext( )-This method returns true if iterator has elements otherwise returns false.
Object next( )-This method returns the next element and throws NoSuchElementException if no element found.
Program-
package in.blogger.tutorialsinn;

import java.util.ArrayList;
import java.util.Iterator;

public class ArraylistIterator {

 public static void main(String[] args) {
  
  //creating an ArrayList
  
  ArrayList<String> arr=new ArrayList<String>();
  
  arr.add("java is");
  arr.add("platform");
  arr.add("independent");
  
  //using while loop
  int i=0;
  System.out.println("using while loop");
  while(i<arr.size()){
   System.out.println(arr.get(i));
   i++;
  }
  
  //using for loop
  System.out.println("using for loop");
  for(i=0;i<arr.size();i++){
   System.out.println(arr.get(i));
   }
  
  //using advance for loop
  System.out.println("using advance for loop");
  for(String str:arr){
   System.out.println(str);
   }
  
  //using Iterator interface
  System.out.println("Using Iterator interface");
  Iterator<String> itr=arr.iterator();
  
  while(itr.hasNext()){
   System.out.println(itr.next());
}
 }
  }


No comments :

Post a Comment