Collections FrameworkJava Interview QuestionsJava_Language_Features

What are Iterators in Java?

Posted On
Posted By admin

Java provides an interface called Iterator that is used to iterate over or loop through the elements in a collection. You can use an iterator on any Collection interfaces or any of its sub interfaces like List or Set.

 

Consider the following code snippet:

	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		for(int i = 0; i &amp;lt; 10; i ++){
			list.add(i+2);
		}
		Iterator<Integer> itr = list.iterator();
		while (itr.hasNext()){
			int i = itr.next();
			System.out.println("i="+i);
		}
	}

 

This code demonstrates how you can use iterator to iterate over a List. Here, we are iterating over a list of integers. But you can use it to iterate over any data type. The iterator method on the list interface returns an iterator instance. In the iterator variable declaration, we need to specify the data type that the iterator will iterate over. In this case, we are specifying Integer.  Once we obtain an iterator, we can use it in a while loop. The iterator has a method called hasNext, this returns true if there are elements left to be iterated. So if there are any elements left, then the while loop is entered. The next method returns the next element in the list. The while loop is repeated till all the elements in the list are exhausted.

 

 

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment