Java Reference
In-Depth Information
The preceding code would produce the following output (the keys are in an unpre-
dictable order since a HashMap is used):
SSN: 239876305
SSN: 867530912
SSN: 504386382
If we instead wanted to loop over every name (every value) stored in the map,
we'd call the values method on the map. The values method returns a reference of
type Collection , not of type Set , because the values may contain duplicates (it's
legal for two keys to map to the same value). If you store the values result in a vari-
able, you should declare that variable as type Collection , with the type of the
map's values between the < and > :
Collection<String> names = ssnMap.values();
for (String name : names) {
System.out.println("name: " + name);
}
The preceding code would produce output such as the following:
name: Stuart Reges
name: Jenny
name: Marty Stepp
You can combine the keys and the values by looping over the keys and then get-
ting the value for each key:
for (int ssn : ssnMap.keySet()) {
String name = ssnMap.get(ssn);
System.out.println(name + "'s SSN is " + ssn);
}
Notice that this code doesn't declare a variable to store the key set, but instead
calls keySet directly in the for-each loop. The code produces the following output:
Stuart Reges's SSN is 239876305
Jenny's SSN is 867530912
Marty Stepp's SSN is 504386382
A related method called entrySet returns objects of a type called Map.Entry that
represents key/value pairs, but we won't explore this method here.
TreeMap versus HashMap
Just as there are two set implementations, HashSet and TreeSet , there are two
flavors of Map collections in Java: HashMap and TreeMap . A HashMap performs a
bit faster than a TreeMap and can store any type of data, but it keeps its keys in a
 
Search WWH ::




Custom Search