Java Reference
In-Depth Information
The
Map values()
method returns the
Collection
of map values; in this
case, a
Collection
of
Stocks
. The
iterator()
method implementation can
then simply return the
Iterator
for this
Collection
:
@Override
public Iterator<Stock> iterator() {
return portfolio.values().iterator();
}
With this implementation of
Iterable<Stock>
, either the legacy a
foreach
loop, or the Java 8
forEach
implementation can be used to iterate a
StockPort-
folio
instance and print each
Stock
:
myPortfolio.forEach(s->System.out.println(s));
The
forEach
method was new to the
Iterable
interface with the release of
Java 8. The method performs the specified action for each element within the
Iter-
able
until all elements have been processed, or the specified action throws an excep-
prints the value of each element within the
myPortfolio Iterable
.
You will notice that
StockPortfolio
also contains the
add(List<Stock>)
method, which allows the portfolio to be populated from a
List
. This method also
uses a
foreach
loop to iterate through the input
List
. Again, this is possible be-
cause
Lists
are
Iterables
. (Note that this method is never called in the code; it
exists only for illustration purposes.)
Note
There's one issue with our implementation of
StockPortfolio
. We have
gone to great lengths to not expose the internal implementation details of our class (the
portfolio map). This allows us to change the implementation without affecting the
StockPortfolio
client code. However, when we implemented
Iterable
, we ef-
fectively exported the underlying portfolio map through the
iterator()
method. As
was demonstrated in Recipe 7-5, an
Iterator
allows the underlying collection to be
modified by calling its
remove()
method. Unfortunately, Java does not provide an
UnmodifiableIterator
class that could be used to wrap an
Iterator
and pre-
vent modification of the underlying
Collection
. However, it would be simple to im-
plement such a class that forwards the
hasNext()
and
next()
calls to the wrapped