CodesJava

Easy learning with example program codes

How to iterate through collection objects?


We can use iterator interface. It is a universal iterator as we can apply it to any Collection object. It provides the functionality of read and remove operations. Collection interface provides iterator() method to get the Iterator object. Iterator interface have following to methods to iterate collection objects.

hasNext(): It returns true if the iteration has more elements.
next(): It returns the next element in the iteration.

Example:

package com.codesjava;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class Test {
  public static void main(String args[]){
	List<String> list = new ArrayList<String>();
	list.add("Jai");
	list.add("Vivek");
	list.add("Mahesh");
	list.add("Vishal");
	list.add("Hemant");
        Iterator<String> iterator = list.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
  }
}

Output

Jai
Vivek
Mahesh
Vishal
Hemant
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki