Iterator

In this chapter you will learn:

  1. What is Iterator and how to use Iterator
  2. Remove an element from Collection using Iterator
  3. Iterable and for each loop

Use Iterator

Each of the collection classes provides an iterator() method that returns an iterator to the start of the collection.

Iterator is a generic interface with the following definition.

interface Iterator<E>

E specifies the type of objects being iterated.

It defines the following methods:

  • 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( ).

By using this iterator object, you can access each element in the collection, one element at a time.

import java.util.Iterator;
import java.util.LinkedList;
//from   j a  va 2  s. c  o  m
public class Main{
    public static void main(String args[]) {
        LinkedList<String> ll = new LinkedList<String>();

        ll.add("A");
        ll.add("ja v a2s.com");
        ll.addLast("B");
        ll.add("C");

        Iterator<String> itr = ll.iterator();
        while (itr.hasNext()) {
            String element = itr.next();
            System.out.print(element + " ");
        }
    }
}

The output:

Remove an element from Collection using Iterator

One good feature of Iterator is that we can remove elements from an Iterator as we are iterating. We can do something like looping through a list and looking for a certain value, once we find that value we can remove the value from the list.

import java.util.ArrayList;
import java.util.Iterator;
/*from   ja v  a 2  s  .  c  o  m*/
public class Main {
  public static void main(String[] args) {
    ArrayList aList = new ArrayList();
    aList.add("1");
    aList.add("2");
    aList.add("3");
    aList.add("4");
    aList.add("java2 s .com");
    System.out.println("ArrayList: ");
    System.out.println(aList);
    Iterator itr = aList.iterator();
    String strElement = "";
    while (itr.hasNext()) {
      strElement = (String) itr.next();
      if (strElement.equals("2")) {
        itr.remove();
        break;
      }
    }
    System.out.println("ArrayList after removal : ");
    System.out.println(aList);
  }
}

The output:

Iterable and for each loop

Because all of the collection classes implement this interface, they can all be operated upon by the for. for can cycle through any collection of objects that implement the Iterable interface.

import java.util.ArrayList;
/*from j  a v a 2 s . c om*/
public class Main {
  public static void main(String args[]) {
    ArrayList<Integer> vals = new ArrayList<Integer>();
    vals.add(1);
    vals.add(2);
    vals.add(3);
    vals.add(4);
    vals.add(5);
  
    for (int v : vals){
      System.out.println(v + " ");      
    }
    int sum = 0;
    for (int v : vals){
      sum += v;      
    }
    System.out.println("Sum of values: " + sum);
  }
}

Next chapter...

What you will learn in the next chapter:

  1. What is ListIterator and how to use ListIterator
Home » Java Tutorial » Collections
Iterator
ListIterator
Collection unmodifiable
Collection synchronized
Collection singleton
Collection max/min value
Empty Collections
Comparator
Comparable
Enumeration
EnumSet
EnumMap Class
PriorityQueue