Iterating Over a Collection – Collections: Part II


Iterating Over a Collection

A common operation on a collection is to iterate over all elements in a collection in order to perform a particular operation on each individual element. We explore several ways in which this operation can be implemented:

  • Using the hasNext() and next() methods of the Iterator<E> interface (p. 793) to access the elements in the underlying collection
  • Using the forEachRemaining() default method of the Iterator<E> interface to access the elements in the underlying collection
  • Using the enhanced for(:) loop to iterate over an object that implements the Iterable<E> interface (see below)
  • Using the forEach() default method of the Iterable<E> interface
  • Using a sequential or parallel stream to iterate over a collection (p. 798)

The Iterable<E> interface defines the methods shown below. The enhanced for(:) loop can be used to iterate over objects that implement this interface. The Collection<E> interface extends the Iterable<E> interface, making all collections iterable.

Click here to view code image

Iterator<E> iterator()                          
From
 Iterable<E>
interface.

Returns an iterator that can be used to iterate over the elements in this collection. Any guarantee regarding the order in which the elements are returned is provided by the individual collection.

Click here to view code image

default void forEach(Consumer<? super T> action) 
From
 Iterable<E>
interface.

With this method, the specified action is performed on each of the remaining elements of an Iterable, unless an exception is thrown, which is then relayed to the caller. The functional interface Consumer<T> is covered in ยง13.7, p. 709.

Example 15.1 illustrates various ways to iterate over a collection that is created at (1). The example uses an ArrayList<E> for a collection of names that are Strings. First an empty ArrayList is created and names are added to the collection. The operation performed on the collection prints each name in uppercase.

Example 15.1 Iterating Over a Collection

Click here to view code image

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
public class IterationOverCollections {
  public static void main(String[] args) {
    // Create a collection of names.                                    (1)
    Collection<String> collectionOfNames = new ArrayList<>();
    Collections.addAll(collectionOfNames, “Alice”, “Bob”, “Tom”,”Dick”,”Harriet”);
    System.out.println(collectionOfNames);
    // Using an explicit iterator.
    Iterator<String> iterator = collectionOfNames.iterator();        // (2)
    while (iterator.hasNext()) {                                     // (3)
      String name = iterator.next();                                 // (4)
      System.out.print(name.toUpperCase() + ” “);
    }
    System.out.println();
    // Using the forEachRemaining() method of the Iterator interface.
    iterator = collectionOfNames.iterator();                         // (5)
    iterator.forEachRemaining(name ->                                // (6)
        System.out.print(name.toUpperCase() + ” “));
    System.out.println();
    // Using the for(:) loop on an Iterable.
    for (String name : collectionOfNames) {                          // (7)
      System.out.print(name.toUpperCase() + ” “);
    }
    System.out.println();
    // Using the forEach() method of the Collection interface.
    collectionOfNames.forEach(name ->                                // (8)
        System.out.print(name.toUpperCase() + ” “));
    System.out.println();
    // Filtering using an explicit iterator.
    iterator = collectionOfNames.iterator();                         // (9)
    while (iterator.hasNext()) {                                     // (10)
      String name = iterator.next();                                 // (11)
      if (name.length() == 3)
        iterator.remove();                                           // (12)
    }
    System.out.println(collectionOfNames);
    // Filtering using the removeIf() method of the Collection interface.
    collectionOfNames.removeIf(name -> name.startsWith(“A”));        // (13)
        System.out.println(collectionOfNames);
    // Using the stream() method of the Collection interface.
    collectionOfNames.stream()                                       // (14)
                     .forEach(name -> System.out.print(name.toUpperCase() + ” “));
    System.out.println();
  }
}

Output from the program:

Click here to view code image

[Alice, Bob, Tom, Dick, Harriet]
ALICE BOB TOM DICK HARRIET
ALICE BOB TOM DICK HARRIET
ALICE BOB TOM DICK HARRIET
ALICE BOB TOM DICK HARRIET
[Alice, Dick, Harriet]
[Dick, Harriet]
DICK HARRIET

Leave a Reply

Your email address will not be published. Required fields are marked *