Java Reference
In-Depth Information
}
}
How It Works
A
Map
is an object that contains a collection of key/value pairs. Maps can be beneficial
when you need to store an index (key) and associate it with a particular value. A
Map
must not contain any duplicate keys, and each key maps to exactly one value. The
source code for the solution (
StockPortfolio1.java
) demonstrates how to add
and remove entries from a
Map
. It also contains the source that is listed in the solution
to this recipe, demonstrating how to iterate over
Map
entries using pre-Java 8 tech-
niques, as well as newer syntax that takes advantage of lambda expressions and
streams.
The
summary()
method uses a
foreach
loop implementation to iterate over the
portfolio map's
Entry
set. To iterate using the pre-Java 8 code, the
Map
entrySet()
method returns a
Set
of
Map.Entry
objects. Within the loop, you
then have access to the key and value for the current
Map.Entry
by calling the re-
spective methods,
key()
and
value()
, on that entry. Use this method of iterating
when you need to access both the map keys and values while iterating, and you don't
need to remove elements from the map. Taking a look at the newer syntax, you can see
that the same iteration can be performed in a single line of code. The newer syntax util-
izes the
forEach()
method, which was added to the
Map
interface in Java 8. It ap-
plies a lambda expression to each entry within the list. The lambda expression takes
both the key and value as arguments, and then prints them out.
The
alertListLegacy()
method uses a
foreach
loop implementation to it-
erate over just the values of the portfolio map. The
Map values()
method returns a
Collection
of the map values; in this case, a
Collection
of
Stocks
. Use this
method of iterating when you only need access to the map values and you don't need to
remove elements from the list. Similarly, if you only need access to the map keys
(again, without the need to remove elements), you can iterate using the
keySet()
method:
for (String symbol : portfolio.keySet()) {
...
}