Iterate java collection


 

Iterate java collection

In this tutorial we will learn about the Iterator interface and its use with the collection interface.We will create an example to print the content of the collection using the iterator() method.

In this tutorial we will learn about the Iterator interface and its use with the collection interface.We will create an example to print the content of the collection using the iterator() method.

  • Collection is the top level interface of the Collection framework.
  • Iterator interface has methods for traversing over the elements of the collection.
  • But Collection doesn't has iterator() method.
  • So create object with the reference of other collection which supports iterator() method


Example
import java.util.*;

public class collection {

	public static void main(String[] args) {
		Collection c = new ArrayList();

		String names[] = { "jack", "rock", "mac", "joe" };
		for (int i = 0; i < names.length; i++) {
			c.add(names[i]);
		}
		Iterator it = c.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output

jack rock mac joe

Ads