Chapter 9. Preliminaries
To understand any framework, it’s as important to have a grasp of the ideas underlying its design as it is to be familiar with the details of its implementation. This chapter explores the concepts behind the Java Collections Framework—concepts that provide essential motivation for the design of the individual collection classes.
Note
The code examples for this chapter can be found at:
https://github.com/MauriceNaftalin/JGC_2e_Book_Code/blob/main/src/main/java/org/jgcbook/chapter09
Iterable and Iterators
For the very common requirement of processing every element of a collection in the same way, we must iterate over it. This ability is provided, in three different ways, by the interface java.lang.Iterable<E>. As this is a superinterface of Collection, its methods are common to every nonmap collection. It exposes three methods:
void forEach(Consumer<? super T> action) |
Performs action for each element of the Iterable |
Iterator<T> iterator() |
Returns an iterator over elements of type T |
Spliterator<T> spliterator() |
Creates a Spliterator over the elements described by this Iterable |
We defer discussion of the purpose of Spliterators to “Parallel Streams”. The other two methods, however are relevant here. The first provides the simplest means of iterating over a collection: for example, to print every element of a collection coll to the terminal, we can simply write:
coll.forEach(System.out::println);
If, however, the body of the iteration is more complex ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access