Different Way to Iterate Over Collection in Java

In java there are multiple ways to iterate, loop through, traverse the elements in collection. For example if you want to display the elements, remove the elements in a given collection then you can implement different ways to iterate, loop or traverse on a given collection like iterator, basic for loop, enhanced for loop etc.

here We will see how to iterate collection using different ways:-

using iterator:-
Iterator enables you to loop through a collection, obtaining or removing elements, to access a collection through iterator we have to obtain the iterator.Each collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, we can access each element in the collection, one element at a time.
Example:-

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

public class Demo{

public static void main(String[] args){
     List<String> list = new ArrayList<String>();
	list.add("A");
	list.add("B");
	list.add("C");
	list.add("D");
	list.add("E");
	list.add("F");
		 
     Iterator<String> iterator = list.iterator();
	while(iterator.hasNext()){
	     Object s =  iterator.next();
	     System.out.println(s);
	}
     }
}

Using for loop:-
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the “for loop” because of the way in which it repeatedly loops until a particular condition is satisfied.

Example:-

List<String> list = new ArrayList<String>();
	list.add("A");
	list.add("B");
	list.add("C");
	list.add("D");
	list.add("E");
	list.add("F");

   for(int i=0; i<list.size(); i++){
	System.out.println(list.get(i));
   }

using enhanced for loop:-
The enhanced for loop was introduced in Java 5 as a simpler way to iterate through all the elements of a Collection.

Example:-

List<String> list = new ArrayList<String>();
		 list.add("A");
		 list.add("B");
		 list.add("C");
		 list.add("D");
		 list.add("E");
		 list.add("F");
		 
		for(String string : list){
			System.out.println(string);
		}

The iterator is useful when you don’t need the index of the element but might need to remove the elements as you iterate.
The for loop is useful when you need the index of the element.
The enhanced for loop comes in use when you do not need any indexes or you are only accessing elements, not removing them or modifying the Collection in any way.

Leave a Comment