Lesson 43 +10 XP

Java Iterator

Java Iterator

An Iterator lets you step through a collection and remove items while looping. You get one from a collection with the iterator() method.

Get an iterator

import java.util.ArrayList;
import java.util.Iterator;

ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");

Iterator<String> it = cars.iterator();

Iterator methods

MethodWhat it does
hasNext()true if there is a next item
next()returns the next item
remove()removes the current item

Loop with an iterator

while (it.hasNext()) {
  System.out.println(it.next());
}

Remove while looping

Iterators are the safe way to delete items while iterating:

while (it.hasNext()) {
  String i = it.next();
  if (i.equals("BMW")) {
    it.remove();
  }
}

TL;DR

  • iterator() returns an Iterator from a collection.
  • hasNext() and next() walk through items.
  • remove() deletes items safely while looping.