How to Iterate a collection using Java Iterator Example

We can iterate an collection using the Iterator object(). The iterator has two methods which will let you to iterate. The hasNext() method returns True when the collection has more elements in it and next() method returns the next element. Lets see how to iterate a collection.

package com.javainterviewpoint;

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

public class JavaIteratorExample 
{
	public static void main(String args[])
	{
		//Create a List (tempList) 
		List tempList = new ArrayList();
		
		//Populating our list
		tempList.add("Java");
		tempList.add("Interview");
		tempList.add("Point");
		tempList.add("JavaIterator");
		tempList.add("Example");
		
		//Get the iterator object using iterator() method of the collection
		Iterator it = tempList.iterator();
		//hasNext() will return true if the collection has more elements
		while(it.hasNext())
		{
			/*next() method may throw a java.util.NoSuchElementException
			 *  if iteration has no more elements.
		     */
			String value= (String)it.next();
			System.out.println(value);
		}
	}
}

Output

Java
Interview
Point
JavaIterator
Example

Leave a Reply

Your email address will not be published. Required fields are marked *