Java Reference
In-Depth Information
7-9. Iterating Over a Map
Problem
You are using one of the Map classes, such as HashMap or TreeMap , and you need
to iterate over the keys, values, or both. You also want to remove elements from the
map while you are iterating over it.
Solution
There are multiple ways to iterate over a Map . The method you choose should depend
on which portions of the map you need to access and whether you need to remove ele-
ments from the map while iterating. The StockPortfolio1 class is a continuation
of the StockPorfolio class shown in the previous recipe. It adds three methods,
summary() , alertList() , and remove(List<String>), that demonstrate
alternative methods for iterating over the portfolio map:
// See StockPortfolio1.java
Map<String, Stock> portfolio = new HashMap<>();
...
public void summary() {
System.out.println("==Legacy technique for traversing
Map.Entry==");
for (Map.Entry<String, Stock> entry
: portfolio.entrySet()) {
System.out.println("Stock = " + entry.getKey()
+ ", Shares = " + entry.getValue().getShares());
}
System.out.println("==Utilization of new foreach and
lambda combination==");
portfolio.forEach((k,v)->System.out.println("Stock
= " + k + ", Shares = " + v.getShares()));
}
/**
* Utilize for loop to traverse Map keys and apply filter
Search WWH ::




Custom Search