Scientech Easy How to iterate ArrayList in Java with Program | Scientech Easy

Thursday, October 25, 2018

How to iterate ArrayList in Java with Program

In this tutorial, we will learn How to iterate ArrayList in Java with example and programs in an easy way and step by step. This topic is very important for interviews. The interviewer can ask one question related to this topic.  

How to iterate ArrayList in Java?

There are five ways by which we can iterate through the elements of an ArrayList. They are as follows:
How to iterate ArrayList in Java, ArrayList iteration.
Ways to iterate ArrayList in Java

1. Using for loop: 
A for loop has the syntax:
   for(initialization; condition; step)
   {
     - - body- - 
     - - - - -- }
Where initialization is a variable declaration. condition is an expression of type boolean, step is an increament/decreament and body is a statement.

The loop is executed as follows:
1. The initialization is executed.
2. The condition is evaluated if it is true, the body is executed. If it is false, the loop terminates.
For example
 // Get the size of the ArrayList.
      int size=al.size();
 // Iterate through all elements.
      System.out.println("for Loop");
      for(int i=0; i<size; i++)
      {
 // Call the get() method to retrun or get the elements on the specified index after iterating.
        String getElement=al.get();
       System.out.println(getElement);
      }

2. Using Enhanced or Advanced for loop
➤ This for loop is introduced in Java 1.5. So if you are using Java 1.5 or later, you can use the enhanced for statement.
➤ In Enhanced for loop, we don't need to increment or decrement.
➤ No size calculation.
➤ We must use the generic concept to iterate the elements of a list.
The syntax of Enhanced for loop:
  for(data_type element : Object reference variable )
    {
       - - - - - -
       - - - - - -
      body
      - - - - - - }

How Enhanced for loop works?

Enhance for loop works in two steps. They are as follows:
1. It iterates through each element in the collection or array.
2. It stores each element in a variable and executes the body.
For example 1
  ArrayList<String> al=new ArrayList<String>();
   for(String element : al)
    {
       System.out.println(element);
      }
 For example 2
   ArrayList<Employee> al=new ArrayList<Employee>();
     for(Employee emp : al )
    { 
      System.out.println(emp.name);
      System.out.println(emp.age);
      }
This for loop is mostly used in the industry.
Let's see a simple program to understand the concept clearly.
Program source code 1:
    package iteratorsTest; import java.util.ArrayList; public class IterateArrayList1 { public static void main(String[] args) { // Create the object of ArrayList of type String. So we can add only the String type element. ArrayList al=new ArrayList(); // Call add() method to add the elements in the list using reference variable al. al.add("A"); al.add("B"); al.add("C"); al.add("D"); al.add("E"); // Displaying original elements in the ArrayList. System.out.println(al); // Iterating ArrayList using for loop. So call size() method to get the size of elements. Since the return type of size method is an integer. Therefore, we will store it using variable elementsize with type int. System.out.println("Using for loop"); int elementsize=al.size(); System.out.println("Size: " +elementsize); for(int i=0; i < al.size(); i++) { // Call get() method to return the elements on specified index after iterating. String getElement=al.get(i); System.out.println(getElement); } al.set(2, "G"); // It will replace the element at position 2 with element G. al.set(3, null); // adding null element at position 3. // Iterating ArrayList using Enhance for loop. System.out.println("Using Enhance for loop"); for(String element:al){ System.out.println(element); } } }
    Output: [A, B, C, D, E] Using for loop Size: 5 A B C D E Using Enhance for loop A B G null E
Note: Iteration through elements in the ArrayList using Enhanced for loop is fail-fast. That means that we can not add or remove the element in the ArrayList during Iteration otherwise it will throw ConcurrentModificationException.



3. Using While loop
Syntax:
   Initialization;
   while(condition) {
         statement1;
         statement2;
         Increment/decrement;
    }
For example
   System.out.println(Iteration of ArrayList using while loop);
int i=0; // initialization.
while(ar.size() > i)
 {
    System.out.println(i);
      i++; // Increment.
    }
Program source code 2:
    package iteratorsTest; import java.util.ArrayList; public class ArrayListUsingWhilelloop { public static void main(String[] args) { ArrayList<Integer> al=new ArrayList<Integer>(); al.add(20); al.add(25); al.add(null); al.add(30); al.add(25); System.out.println(al); // Iteration of ArrayList using while loop. System.out.println("Iteration using while loop"); int i=0; while(al.size()>i){ Integer itr=al.get(i); System.out.println(itr); i++; } } }
    Output: [20, 25, null, 30, 25] Iteration using while loop 20 25 null 30 25
4. Using Iterator
iterator() method is used to iterate over elements in the ArrayList in Java. iterator() method is useful when we want to remove the last element during iteration. The Iterator interface defines three methods. They are as follows:
1. hasNext(): This method returns true if the iteration has more elements in the forward direction. 
2. next(): It returns the next element in the iteration. If the iteration has no more elements then it will throw "NoSuchElementException".
3. remove(): remove() method removes the last element returned by iterator. This method must be called after calling next() method otherwise, it will throw "IllegalStateException". 
Program source code 3:
    package iteratorsTest; import java.util.ArrayList; import java.util.Iterator; public class RemoveTest { public static void main(String[] args) { ArrayList<String> al=new ArrayList<String>(); al.add("Apple"); al.add("Mango"); al.add("Banana"); al.add("Guava"); al.add("Pineapple"); System.out.println(al); // It will print all elements at a time. System.out.println("Iteration using iterator concept."); // Create the object of Iterator by calling iterator() method using reference variable al. // At the beginning, itr(cursor) will point to index just before the first element in al. Iterator<String> itr=al.iterator(); // Checking the next element availability using reference variable itr. while(itr.hasNext()){ // Moving cursor to next element using reference variable itr. String str=itr.next(); System.out.println(str); // Removing the pineapple element. if(str.equals("Pineapple")){ itr.remove(); System.out.println("After removing pineapple element"); System.out.println(al); } } } }
    Output: [Apple, Mango, Banana, Guava, Pineapple] Iteration using iterator concept. Apple Mango Banana Guava Pineapple After removing pineapple element [Apple, Mango, Banana, Guava]
Note: iterator returned by ArrayList is a fail-fast. That means that if we add element or remove an element in the ArrayList during the Iteration then it will throw "ConcurrentModificationException".because the loop internally creates a fail-fast iterator which throws an exception whenever any structural modification in the underlying data structure.
Let's see a simple program to understand the fail-fast concept in ArrayList.
Program source code 4:
    package iteratorsTest; import java.util.ArrayList; import java.util.Iterator; public class AddingElementUsingIteration { public static void main(String[] args) { ArrayList<String> al=new ArrayList<String>(); al.add("Lion"); al.add("Tiger"); al.add("Elephant"); al.add("Bear"); Iterator<String> itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); // Adding element using the iterator method. Since the return type of add() method is boolean. Therefore, we will store it using variable b with data type boolean. boolean b=al.add("Leopard"); // Compile time error. It will throw ConcurrentModificationException. System.out.println(b); } } }
    Output: Exception in thread "main" java.util.ConcurrentModificationException
5. Using ListIterator
ListIterator is used to iterate the elements of ArrayList in both forward as well as backward direction. Using ListIterator, we can start the iteration from a specific element in the ArrayList. We can perform different kinds of operations such as read, remove, replacement(current object), and the addition of the new objects.

ListIterator interface defines 9 methods in Java. They are as follows:
Since ListIterator is the child interface of Iterator. Therefore, all the methods of Iterator are available by default to the ListIterator. ListIterator interface has total 9 methods. They are as follows:
Forward direction
1. public boolean hasNext()
2. public Object next()
3. public int nextIndex(): It returns the index of the next element in the list. The return type of this method is an integer.

Backward direction
4. public boolean hasPrevious(): It checks that the list has more elements in the backward direction. If the list has more elements, it will return true. The return type is boolean.
5. public Object previous(): It returns the previous element in the list and moves the cursor position backward direction. The return type is Object.
6. public int previousIndex(): It returns the index of the previous element in the list. The return type is an Integer.

Other capability methods
7. public void remove(): Remove the last element returned by next() or previous() from the list. The return type is 'nothing'.
8. public void set(Object o): It replaces the last element returned by next() or previous() with the new element. 
9. public void add(Object o): Insert a new element in the list.
Let's see a simple example program to understand the concepts. 

Program source code 5:
    package iteratorsTest; import java.util.ArrayList; import java.util.ListIterator; public class ArrayListUsingListIterator { public static void main(String[] args) { ArrayList<String> al=new ArrayList<String>(); al.add("First"); al.add("Second"); al.add("Third"); al.add("Fourth"); al.add("Fifth"); System.out.println(al); // Iterating using ListIterator. // Call listIterator() method to create the object of ListIterator using reference variable al. ListIterator litr=al.listIterator(); // Here we are not using generic. Therefore, Typecasting is required. // Checking the next element availability in the forward direction using reference variable litr. System.out.println("Iteration in the forward direction"); while(litr.hasNext()){ // Moving cursor to next element in the forward direction using reference variable litr. Object o=litr.next(); String str=(String)o; // Typecasting is required because the return type of next() method is an Object. System.out.println(str); } // Checking the previous element in the backward direction using reference variable litr1. System.out.println("Iteration in the backward direction."); while(litr.hasPrevious()){ // Moving cursor to the previous element in the backward direction. Object o=litr.previous(); String str1=(String)o; // Typecasting. System.out.println(str1); } } }
    Output: [First, Second, Third, Fourth, Fifth] Iteration in the forward direction First Second Third Fourth Fifth Iteration in the backward direction. Fifth Fourth Third Second First
Program source code 6: 
    package iteratorsTest; import java.util.ArrayList; import java.util.ListIterator; public class ArrayListUsingListIteratorTest { public static void main(String[] args) { ArrayList<String> al=new ArrayList<String>(); al.add("One"); al.add("Two"); al.add("Three"); al.add("Nine"); al.add("Five"); al.add("Seven"); System.out.println(al); ListIterator<String> litr=al.listIterator(); while(litr.hasNext()){ String str=litr.next(); if(str.equals("Nine")){ litr.remove(); litr.add("Four"); System.out.println(al); } else if(str.equals("Seven")){ litr.set("Six"); System.out.println(al); } }} }
    Output: [One, Two, Three, Nine, Five, Seven] [One, Two, Three, Four, Five, Seven] [One, Two, Three, Four, Five, Six]
Program source code 7: In this example program, we will iterate through a specific element '4' in the list. We will add the number from 0 to 9 as an element in the list using for loop.
    package iteratorsTest; import java.util.ArrayList; import java.util.ListIterator; public class SpecificElementTest { public static void main(String[] args) { ArrayList<Integer> al=new ArrayList<Integer>(); for(int i=0 ; i<=9 ; i++){ al.add(i); } System.out.println(al); ListIterator<Integer> litr=al.listIterator(4); // Iterating through a specific element '4'. while(litr.hasNext()){ Integer it=litr.next(); System.out.println(it); } while(litr.hasPrevious()){ al.add(20); // It will throw ConcurrentModificationException because we can not add element in the ArrayList during Iteration. Integer it1=litr.next(); System.out.println(it1); } } }
    Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 4 5 6 7 8 9 Exception in thread "main" java.util.ConcurrentModificationException
Note: ListIterator returned by ArrayList is also fail-fast.It will throw ConcurrentModificationException. That is we cannot add or remove element in the ArrayList during Iteration. 

More on Iterators
1. Iterators in Java | Types & Example programs.

Final words:
We hope that this article will help you to learn How to iterate ArrayList in Java? with example programs. This article has covered almost all the practical example programs with concepts related to this topic. All programs are very imporant so you practice all the above programs.

Popular