ArrayList Iterator | traversal of ArrayList - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Saturday, November 26, 2016

ArrayList Iterator | traversal of ArrayList

In this post, We will see about some other methods of Java ArrayList and different way to traverse and iterate over Java ArrayList.

I strongly recommend to read about common methods of Java ArrayList.

Java ArrayList Iterator

Iterator is an interface in Java collection framework. The iterator returned by this class's iterator() method fail-fast. If the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove() method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Bellow is simple example of ArrayList iterator.

package com.walking.techie;

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

public class ArrayListIteratorDemo {

 public static void main(String[] args) {
  List<Integer> numbers = new ArrayList<Integer>();

  // add numbers from 1 to 10 in ArrayList
  for (int i = 1; i <= 10; i++) {
   numbers.add(i);
  }
  Iterator<Integer> iterator = numbers.iterator();
  System.out.print("Element of numbers array list: ");

  while (iterator.hasNext()) {
   int temp = iterator.next();
   System.out.print(temp + " ");
  }

  // modification of array list through remove method of iterator
  iterator = numbers.iterator();
  while (iterator.hasNext()) {
   int temp = iterator.next();
   if (temp % 2 == 0)
    iterator.remove();
  }
  System.out.println("\nnumbers list after modifications: " + numbers);

  // Now,changing it's structure while iterating

  iterator = numbers.iterator();
  while (iterator.hasNext()) {
   int temp = iterator.next();
   System.out.print(temp + " ");
   if (temp == 9) {
    System.out.println();
    numbers.add(11); // ConcurrentModificationException
   }
  }
 }
}

Output of above program is shown below:

Element of numbers array list: 1 2 3 4 5 6 7 8 9 10
numbers list after modifications: [1, 3, 5, 7, 9]
1 3 5 7 9
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
 at java.util.ArrayList$Itr.next(ArrayList.java:851)
 at com.walking.techie.ArrayListIteratorDemo.main(ArrayListIteratorDemo.java:37)

Java ArrayList ListIterator

we can use ListIterator to traverse in both direction. The iterator returned by this class's listIterator(int) or listIterator() methods are fail-fast. If the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove() or add(Object) methods, the iterator will throw a ConcurrentModificationException.

package com.walking.techie;

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

public class ArrayListListIteratorDemo {

 public static void main(String[] args) {
  List<Integer> numbers = new ArrayList<Integer>();

  // add numbers from 1 to 10 in ArrayList
  for (int i = 1; i <= 10; i++) {
   numbers.add(i);
  }
  ListIterator<Integer> listIterator = numbers.listIterator();
  System.out.print("Element of numbers array list: ");
  while (listIterator.hasNext()) {
   int temp = listIterator.next();
   System.out.print(temp + " ");
  }

  // modification of array list through remove method of iterator
  listIterator = numbers.listIterator();
  while (listIterator.hasNext()) {
   int temp = listIterator.next();
   if (temp % 2 == 0) {
    listIterator.remove();
    listIterator.add(temp * 10);
   }
  }

  System.out.println("\nnumbers list after modifications: " + numbers);

  // traverse the array list in backward direction

  listIterator = numbers.listIterator(numbers.size());
  System.out.print("Backward direction traversal of numbers list: ");
  while(listIterator.hasPrevious()){
   int temp=listIterator.previous();
   System.out.print(temp+ " ");
  }
  System.out.println();

  // below code will throw ConcurrentModificationException
  listIterator = numbers.listIterator();
  while (listIterator.hasNext()) {
   int temp = listIterator.next();
   System.out.print(temp + " ");
   if (temp == 9) {
    System.out.println();
    numbers.add(25);// ConcurrentModificationException
   }
  }
 }

}

Output of above program is shown below:

Element of numbers array list: 1 2 3 4 5 6 7 8 9 10
numbers list after modifications: [1, 20, 3, 40, 5, 60, 7, 80, 9, 100]
Backward direction traversal of numbers list: 100 9 80 7 60 5 40 3 20 1
1 20 3 40 5 60 7 80 9
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
 at java.util.ArrayList$Itr.next(ArrayList.java:851)
 at com.walking.techie.ArrayListListIteratorDemo.main(ArrayListListIteratorDemo.java:48)

Java ArrayList forEach

Java ArrayList forEach method was added in Java 8. It's useful when you want to perform same action on all the elements. The method argument Consumer is a functional interface. Below is an example of forEach method.

package com.walking.techie;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class ArrayListForEachDemo {

 public static void main(String[] args) {
  List<Integer> numbers = new ArrayList<Integer>();

  // add numbers from 1 to 10 in ArrayList
  for (int i = 1; i <= 10; i++) {
   numbers.add(i);
  }

  Consumer<Integer> consumer = new ArrayListForEachDemo().new MyConsumer<Integer>();
  numbers.forEach(consumer);
 }

 private class MyConsumer<T> implements Consumer<Integer> {

  @Override
  public void accept(Integer t) {
   System.out.println("consuming " + t);
  }
 }
}

Output of above program is shown below:

consuming 1
consuming 2
consuming 3
consuming 4
consuming 5
consuming 6
consuming 7
consuming 8
consuming 9
consuming 10

Java ArrayList index based traversal

All of us familiar with the indexed base travering in the array. Java ArrayList is dynamic array with index based traversal. Below is the simple program to traverse Java ArrayList using get method of it.

package com.walking.techie;

import java.util.ArrayList;
import java.util.List;

public class ArrayListIndexBasedDemo {
 public static void main(String[] args) {
  List<Integer> numbers = new ArrayList<Integer>();

  // add numbers from 1 to 10 in ArrayList
  for (int i = 1; i <= 10; i++) {
   numbers.add(i);
  }

  //simple way to traverse array list using index
  System.out.print("index based traversal of array list: [ ");
  for(int i=0;i<numbers.size();i++){
   System.out.print(numbers.get(i)+" ");
  }
       System.out.println("]");
 }
}

Output of above program is shown below:

index based traversal of array list: [ 1 2 3 4 5 6 7 8 9 10 ]

No comments :

Post a Comment