Iterate Loop List or ArrayList in Java - Java @ Desk

Monday, March 24, 2014

Iterate Loop List or ArrayList in Java

Iterate Loop List or ArrayList in Java in the following ways:

1) Normal for loop
2) Advance for loop
3) Using while loop
4) Using java.util.Iterator
5) Using java.util.ListIterator
6) Using remove function of List - Using remove method will make the list empty

Following is the set of Strings added in the List
1) Mesothelioma law firm
2) Sell annuity payment
3) Annuity settlements
4) Car donate
5) Motor insurance quotes
6) Auto accident attorney
7) Personal Loans

Sample Implementation

package test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class IterateLoopArrayList {

 public static void main(String args[]) {
  List<String> list = new ArrayList<String>();
  list.add("Mesothelioma law firm");
  list.add("Sell annuity payment");
  list.add("Annuity settlements");
  list.add("Car donate");
  list.add("Motor insurance quotes");
  list.add("Auto accident attorney");
  list.add("Personal Loans");

  int listSize = list.size();

  System.out
    .println("\n*****************Normal for loop*******************");
  for (int i = 0; i < listSize; i++) {
   System.out.println(list.get(i));
  }

  System.out
    .println("\n*******************Advance for loop*******************");
  for (String string : list) {
   System.out.println(string);
  }

  System.out
    .println("\n*******************Using while loop*******************");
  int j = 0;
  while (list.size() > j) {
   System.out.println(list.get(j));
   j++;
  }

  System.out
    .println("\n*******************Using Iterator*******************");
  Iterator<String> iterator = list.iterator();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }

  System.out
    .println("\n*******************Using List Iterator*******************");
  ListIterator<String> listIterator = list.listIterator();
  while (listIterator.hasNext()) {
   System.out.println(listIterator.next());
  }

  System.out
    .println("\n*******************Using remove function of list*******************");
  while (list.size() > 0) {
   System.out.println(list.remove(0));
  }
 }
}






No comments:

Post a Comment