Iterator vs forEach in Java


Collections can be iterated easily using two approaches.

  • Using for-Each loop − Use a foreach loop and access the array using object.

  • Using Iterator − Use a foreach loop and access the array using object.

Differences

  • ConcurrentModificationException − Using for-Each loop, if an object is modified, then ConcurrentModificationException can occur. Using iterator, this problem is elliminated.

  • Size Check − Using for-Each, size check is not required. Using iterator if hasNext() is not used properly, NoSuchElementException can occur.

  • Performance − Performance is similar for both cases.

Following is an example of using above ways.

Example

 Live Demo

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

public class Tester {

   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>();
      list.add(1);list.add(2);list.add(3);
      list.add(4);list.add(5);list.add(6);

      System.out.println("List: ");
      //Way 1:
      for (int i : list) {
         System.out.print(i + " ");
      }

      Iterator<Integer> listIterator = list.iterator();
      System.out.println("
List: ");       while(listIterator.hasNext()){          System.out.print(listIterator.next() + " ");       }    } }

Output

List:
1 2 3 4 5 6
List:
1 2 3 4 5 6

Updated on: 23-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements