Java Reference
In-Depth Information
Table 11.5
Useful Methods of Maps
Method
Description
Removes all keys and values from a map
clear()
Returns
true
if the given key maps to some value in this map
containsKey(key)
Returns
true
if some key maps to the given value in this map
containsValue(value)
Returns the value associated with this key, or
null
if not found
get(key)
Returns
true
if this collection contains no keys or values
isEmpty()
Returns a
Set
of all keys in this map
keySet()
Associates the given key with the given value
put(key, value)
Adds all key/value mappings from the given map to this map
putAll(map)
Removes the given key and its associated value from this map
remove(key)
Returns the number of key/value mappings in this map
size()
Returns a
Collection
of all values in this map
values()
Unlike most collections, a map doesn't have an
iterator
method, because it wouldn't
be clear what you wanted to examine. The keys? The values? Both? Instead, maps
have a pair of methods called
keySet
and
values
that respectively return a
Set
of
all keys in the map and a
Collection
of all values in the map. These are sometimes
called
collection views
of a map because each is a collection that exists conceptually
within the map.
For example, consider a map that associates people's social security numbers with
their names. In other words, the map's keys are nine-digit social security numbers
and its values are names. We could create the map with the following code:
Map<Integer, String> ssnMap = new HashMap<Integer, String>();
ssnMap.put(867530912, "Jenny");
ssnMap.put(239876305, "Stuart Reges");
ssnMap.put(504386382, "Marty Stepp");
If we wanted to write a loop that printed the social security numbers of every
person in the map, we could then call the
keySet
method on the map. This method
returns a
Set
containing every key from the hash tableāin this case, every
int
for
a person's number. If you store the
keySet
in a variable, you should declare that
variable as type
Set
, with the type of the map's keys between the
<
and
>
brackets:
Set<Integer> ssnSet = ssnMap.keySet();
for (int ssn : ssnSet) {
System.out.println("SSN: " + ssn);
}
Search WWH ::
Custom Search