Java Reference
In-Depth Information
If you also need to also access the map value while iterating using the key set,
avoid the following, as it is very inefficient. Instead, use the method of iteration shown
in the summary() method.
for (String symbol : portfolio.keySet()) {
Stock stock = portfolio.get(symbol);
...
}
Taking a look at the alertList() method in the solution, you can see that the
same iteration can be performed with much less work using a combination of streams,
filters, and collectors. See Recipe 7-8 for more details regarding streams and the
Stream API. In alertList() , a stream is generated, and then a filter, in the form of
a lambda expression, is applied to that stream. Finally, a collector is applied to the fil-
ter, creating a List<Stock> to return.
The remove(List<String>) method takes a list of stock symbols represent-
ing the stocks to be removed from the portfolio. This method iterates over the portfolio
map keys using the keySet() iterator, removing the current map entry if it is one of
the stocks specified for removal. Notice that the map element is removed through the
iterator's remove() method. This is possible because the key set is backed by the
map, so changes made through the key set's iterator are reflected in the map. You could
also iterate over the portfolio map using its values() iterator:
Iterator<Stock> valueIter = portfolio.values().iterator();
while (valueIter.hasNext()) {
if (sellList.contains(valueIter.next().getSymbol())) {
valueIter.remove();
}
}
As with the key set, the values collection is backed by the map, so calling re-
move() through the values iterator will result in removal of the current entry from the
portfolio map.
In summary, if you need to remove elements from a map while iterating over the
map, iterate using one of the map's collection iterators and remove map elements
through the iterator, as shown in the remove(List<String>) method. This is the
only safe way to remove map elements during iteration. Otherwise, if you don't need to
Search WWH ::




Custom Search