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


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

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