×
☰ See All Chapters

Iterating Collection in Java

Collection framework provides 3 interfaces to visit the elements of a collection.

  1. Enumeration:  Can be used with only legacy classes. It was added in Java 1.0 

  2. Iterator: Can be used with all classes. It was added in Java 1.2. 

  3. ListIterator: Can only be used with classes which implement List interface.(Vector, ArrayList and LinkedList). It was also added in Java 1.2. 

Enumeration

Iterator

ListIterator

Enumeration is a legacy interface.

Iterator is a collection framework interface.

ListIterator is a collection framework interface.

We cannot add, remove or replace the elements of collection using Enumeration.

We can remove the elements in collection using Iterator.

We can add, remove and replace the elements using ListIterator.

We can iterate through only in forward direction through a collection.

Using Iterator you can visit the elements of a collection only in the forward direction.

Using Iterator you can visit the elements of a collection both in the forward and reverse direction.

It can be used to iterate through only legacy collection classes (Vector, Hashtable, etc).

It is available to all the classes in collection frame work.

It is available only to classes which implement List interface. (ArrayList, LinkedList, Vector)

Using Iterator

Each of the collection classes provides an iterator( ) method that returns an iterator (object for iterator interface) to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.

In general, to use an iterator to cycle through the contents of a collection, follow these steps:

  • Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method. 

  • Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. 

  • Within the loop, obtain each element by calling next( ). 

The Methods Defined by Iterator

Method

Description

boolean hasNext( )

Returns true if there are more elements. Otherwise, returns false.

E next( )

 

Returns the next element. Throws NoSuchElementException if there is not a next element.

void remove( )

 

Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).

Example for Iterator

IteratotrDemo.java

import java.util.ArrayList;

import java.util.Iterator;

 

public class IteratotrDemo {

        public static void main(String[] args) {

                // iterating through dissimilar elements in ArrayList

                //ArrayList can be replaced with any collection class that allows  dissimilar/similar elements.

                ArrayList al1 = new ArrayList();

                al1.add("6000");

                al1.add(new Integer(100));

                al1.add(new Double(1000.555));

                Iterator itr1 = al1.iterator();

                while (itr1.hasNext()) {

                        Object e = (Object) itr1.next();

                        if (e instanceof String) {

                                String str = e.toString();

                                System.out.println("Value of String is :" + str);

                        } else if (e instanceof Integer) {

                                Integer i = (Integer) e;

                                System.out.println("Value of Integer is :" + i);

                        } else if (e instanceof Double) {

                                Double d = (Double) e;

                                System.out.println("Value of Double is :" + d);

                        }

                }

                // iterating through similar elements in ArrayList

                //Can replace with any collection class .

                ArrayList al2 = new ArrayList();

                al2.add("100");

                al2.add("101");

                al2.add("102");

                al2.add("103");

                al2.add("104");

                Iterator itr2 = al2.iterator();

                while (itr2.hasNext()) {

                        Object e = (Object) itr2.next();

                        System.out.println(e);

                        String s = (String) e;

                        System.out.println(s);

                }

 

                // using enhanced for loop

                for (Object e : al1) {

                        System.out.println(e);

                }

                //Drawbacks of Java Enhanced For loop

                //It’s important to note that the enhanced for loop can’t be used everywhere. You can’t use the enhanced for loop:

                //* To remove elements as you traverse collections

                //* To modify the current slot in an array or list

                //* To iterate over multiple collections or arrays

        }

}

Output:

Value of String is :6000

Value of Integer is :100

Value of Double is :1000.555

100

100

101

101

102

102

103

103

104

104

Iterating ArrayList inside ArrayList

import java.util.ArrayList;

import java.util.Iterator;

 

public class IterateArrayListInArrayListDemo {

        public static void main(String[] args) {

                // create 3 ArrayList

                ArrayList  list1 = new ArrayList();

                list1.add("100");

                list1.add("101");

                list1.add("102");

                list1.add("103");

                list1.add("104");

                System.out.println("First List" + list1);

 

                ArrayList  list2 = new ArrayList();

                list2.add("200");

                list2.add("201");

                list2.add("202");

                list2.add("203");

                list2.add("204");

                System.out.println("Second List" + list1);

 

                ArrayList  list3 = new ArrayList();

                list3.add("300");

                list3.add("301");

                list3.add("302");

                list3.add("303");

                list3.add("304");

                System.out.println("Third List" + list1);

                // add all three ArrayList into a single ArrayList

                ArrayList  list = new ArrayList();

                list.add(list1);

                list.add(list2);

                list.add(list3);

                System.out.println("List of Lists" + list);

                // Accessing the elements in final list

                Iterator itr = list.iterator();

                while(itr.hasNext()){

                        Object e = itr.next();

                        ArrayList arl = (ArrayList)e;

                        Iterator i = arl.iterator();

                        while(i.hasNext()){

                                Object obj = i.next();

                                String s = (String)obj;

                                System.out.print(s + " ");

                        }

                        System.out.println();

                }

}

}

Output:

Second List[100, 101, 102, 103, 104]

Third List[100, 101, 102, 103, 104]

List of Lists[[100, 101, 102, 103, 104], [200, 201, 202, 203, 204], [300, 301, 302, 303, 304]]

100 101 102 103 104

200 201 202 203 204

300 301 302 303 304

Iterate Collection with user defined collection

class Student {

        private int studentId;

        private String name;

        public int getStudentId() {

                return studentId;

        }

        public void setStudentId(int studentId) {

                this.studentId = studentId;

        }

        public String getName() {

                return name;

        }

        public void setName(String name) {

                this.name = name;

        }

        @Override

        public String toString() {

                return "Student [studentId=" + studentId + ", name=" + name + "]";

        }

}

public class IteratotrDemo {

        public static void main(String[] args) {

                Student s1= new Student();

                s1.setName("Manu M");

                s1.setStudentId(1111);

                Student s2= new Student();

                s2.setName("AdiTemp");

                s2.setStudentId(2222);

                ArrayList al=new ArrayList();

                al.add(s1);

                al.add(s2);

                System.out.println(al);

                Iterator itr=al.iterator();

                while(itr.hasNext()){

                        Object e = itr.next();

                        Student s=(Student)e;

                        System.out.println(s.getName());

                        System.out.println(s.getStudentId());

                }

        }

}

Output:

[Student [studentId=1111, name=Manu M], Student [studentId=2222, name=AdiTemp]]

Manu M

1111

AdiTemp

2222

 

Using ListIterator

For collections that implement List, we can also obtain an iterator by calling listIterator( ).

ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.

In general, to use an ListIterator to cycle through the contents of a collection, follow these steps:

> Obtain an object for  ListIterator  interface (to the start of the collection) by calling the collection’s listIterator( ) method.

>  Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.

>  Within the loop, obtain each element by calling next( ).

The Methods Defined by ListIterator

Method

Description

void add(E obj)

 

Inserts obj into the list in front of the element that will be returned

by the next call to next( ).

boolean hasNext( )

Returns true if there is a next element. Otherwise, returns false.

boolean hasPrevious( )

Returns true if there is a previous element. Otherwise, returns false.

E next( )

 

Returns the next element. A NoSuchElementException is thrown

if there is not a next element.

int nextIndex( )

 

Returns the index of the next element. If there is not a next element, returns the size of the list.

E previous( )

 

Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.

int previousIndex( )

 

Returns the index of the previous element. If there is not a previous

element, returns -1

void remove( )

 

Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.

void set(E obj)

 

Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).

ListIterator Example

ListIteratorDemo.java

import java.util.ArrayList;

import java.util.Iterator;

import java.util.ListIterator;

 

public class ListIteratorDemo {

        public static void main(String[] args) {

                // iterating through dissimilar elements in ArrayList

                // display the list in forward

                ArrayList al1 = new ArrayList();

                al1.add("6000");

                al1.add(new Integer(100));

                al1.add(new Double(1000.555));

                ListIterator itr1 = al1.listIterator();

                while (itr1.hasNext()) {

                        Object e = (Object) itr1.next();

                        if (e instanceof String) {

                                String str = e.toString();

                                System.out.println("Value of String is :" + str);

                        } else if (e instanceof Integer) {

                                Integer i = (Integer) e;

                                System.out.println("Value of Integer is :" + i);

                        } else if (e instanceof Double) {

                                Double d = (Double) e;

                                System.out.println("Value of Double is :" + d);

                        }

                }

                // now, display the list backwards

                while (itr1.hasPrevious()) {

                        Object e = (Object) itr1.previous();

                        if (e instanceof String) {

                                String str = e.toString();

                                System.out.println("Value of String is :" + str);

                        } else if (e instanceof Integer) {

                                Integer i = (Integer) e;

                                System.out.println("Value of Integer is :" + i);

                        } else if (e instanceof Double) {

                                Double d = (Double) e;

                                System.out.println("Value of Double is :" + d);

                        }

                }

 

                // iterating through similar elements in ArrayList

                ArrayList al2 = new ArrayList();

                al2.add("100");

                al2.add("101");

                al2.add("102");

                al2.add("103");

                al2.add("104");

                ListIterator itr2 = al2.listIterator();

                while (itr2.hasNext()) {

                        Object e = (Object) itr2.next();

                        System.out.println(e);

                        String s = (String) e;

                        System.out.println(s);

                }

        }

}

Output:

Value of String is :6000

Value of Integer is :100

Value of Double is :1000.555

Value of Double is :1000.555

Value of Integer is :100

Value of String is :6000

100

100

101

101

102

102

103

103

104

104

 


All Chapters
Author