Java Reference
In-Depth Information
// Each key must map to a single value. But keys may map to the
// same value
for
(
int
i
=
0
;
i
<
words
.
length
;
i
++)
{
m
.
put
(
words
[
i
].
toUpperCase
(),
i
);
}
// The putAll() method copies mappings from another Map
m
.
putAll
(
singleton
);
// Query the mappings with the get() method
for
(
int
i
=
0
;
i
<
words
.
length
;
i
++)
{
if
(
m
.
get
(
words
[
i
])
!=
i
)
throw
new
AssertionError
();
}
// Key and value membership testing
m
.
containsKey
(
words
[
0
]);
// true
m
.
containsValue
(
words
.
length
);
// false
// Map keys, values, and entries can be viewed as collections
Set
<
String
>
keys
=
m
.
keySet
();
Collection
<
Integer
>
values
=
m
.
values
();
Set
<
Map
.
Entry
<
String
,
Integer
>>
entries
=
m
.
entrySet
();
// The Map and its collection views typically have useful
// toString methods
System
.
out
.
printf
(
"Map: %s%nKeys: %s%nValues: %s%nEntries: %s%n"
,
m
,
keys
,
values
,
entries
);
// These collections can be iterated.
// Most maps have an undefined iteration order (but see SortedMap)
for
(
String
key
:
m
.
keySet
())
System
.
out
.
println
(
key
);
for
(
Integer
value:
m
.
values
())
System
.
out
.
println
(
value
);
// The Map.Entry<K,V> type represents a single key/value pair in a map
for
(
Map
.
Entry
<
String
,
Integer
>
pair
:
m
.
entrySet
())
{
// Print out mappings
System
.
out
.
printf
(
"'%s' ==> %d%n"
,
pair
.
getKey
(),
pair
.
getValue
());
// And increment the value of each Entry
pair
.
setValue
(
pair
.
getValue
()
+
1
);
}
// Removing mappings
m
.
put
(
"testing"
,
null
);
// Mapping to null can "erase" a mapping:
m
.
get
(
"testing"
);
// Returns null
m
.
containsKey
(
"testing"
);
// Returns true: mapping still exists
m
.
remove
(
"testing"
);
// Deletes the mapping altogether
m
.
get
(
"testing"
);
// Still returns null
m
.
containsKey
(
"testing"
);
// Now returns false.
// Deletions may also be made via the collection views of a map.
// Additions to the map may not be made this way, however.
m
.
keySet
().
remove
(
words
[
0
]);
// Same as m.remove(words[0]);