Difference between java iterator and for each

In this article, we will discuss the java iterator vs foreach loop. We will see the difference between for each loop and Iterator.

1. How java iterator vs foreach works

Iterator: Iterator can be used only for Collection. Iterator is an abstract method of an Iterable interface. The body of iterator() method define in implemented class like ArrayList, Hashmap, etc

  List<Integer> numbers = Arrays.asList(1,2,3,4,5);
    	  Iterator iterator = numbers.iterator();
    	  while(iterator.hasNext())
    	  {
    		  System.out.println(iterator.next());
    	  }

foreach: By use of for each loop we can traverse collection and Arrays.

List<Integer> numbers = Arrays.asList(1,2,3,4,5);
    	  
    	  for(int n : numbers)
    	  {
    		  System.out.println(n);
    	  }

You can use forEach() method that define in the Iterable interface in Java 8.

List<Integer> numbers = Arrays.asList(1,2,3,4,5);  
numbers.forEach(n -> System.out.println(n));

2. ConcurrentModificationException(Modify Collections)

By use of forEach loop, you can’t modify the Collection. So, By means modification is removing an element or changing the content of an item stored in the collection.

List<Integer> numbers = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
    	  for(Integer n : numbers)
    	  {
    		  if(n == 2)
    			  numbers.remove(2);
    	  }
System.out.println(numbers);

By the use of iterator, we can modify the Collection. Because for-each loop internally uses the iterator, but it is not exposed to the user. Thus we can’t modify the items in the collections.

 List<Integer> numbers = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
    	  Iterator<Integer> iterator = numbers.iterator();
    	  while(iterator.hasNext())
    	  {
    		  if(iterator.next() == 2)
    		  {
    			  iterator.remove();
    		  }
    	  }
    	  System.out.println(numbers);

3. When to use

Iterator uses only for Collection. Because iterator() method define in the Iterable interface and all collection classes inherit it. You can’t use an iterator on Arrays.

foreach can be used for Collection and non-collection(Array).

4. Nested loop

If you want to perform some tasks and want to use nested loops in the program. Then, you should use the for loop instead of the iterator. Because of the next() method of iterator points to the next position each time. You might get confused.

5. Exception can occur

If you are using for-Each, then you don’t care about the size. Even you are traversing any collections.

But if you use Iterator and hasNext() not used properly, NoSuchElementException can occur.

6. Java iterator vs foreach loop Performance

The for-each loop or iterator gives the same performance when traversing a collection. By mean of performance, we mean the time complexity of both these traversals.

3 thoughts on “Difference between java iterator and for each”

  1. Alternatively we can also modify a collection in a foreach loop :
    Concurrent Collection classes can be modified safely, they will not throw ConcurrentModificationException.
    In case of CopyOnWriteArrayList, iterator doesn’t accommodate the changes in the list and works on the original list.
    In case of ConcurrentHashMap, the behaviour is not always the same.

  2. I am able to modify elements using for each loop in Hash set. its not throwing any exception for me?? then what is the diference between for each loop and iterator?

Leave a Comment