Java HashMap get() Method
The get() method retrieves the value corresponding to the specified key.
The syntax of the get() method is:
hashmap.get(Object key)
**Note:** hashmap is an object of the HashMap class.
Parameter Description:
- key - the key
Return Value
Returns the value associated with the specified key.
Example
The following example demonstrates the use of the get() method:
Example
import
java.util.HashMap
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create a HashMap
HashMap
<
Integer
, String
sites
=
new
HashMap
<>
(
)
;
// Add some elements to the HashMap
sites.
put
(
1
,
"Google"
)
;
sites.
put
(
2
,
"Runoob"
)
;
sites.
put
(
3
,
"Taobao"
)
;
System
.
out
.
println
(
"sites HashMap: "
sites
)
;
// Get the value
String
value
=
sites.
get
(
1
)
;
System
.
out
.
println
(
"value for key 1: "
value
)
;
}
}
The output of the above program is:
sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
key 1 对应的 value: Google
**Note:** We can also use HashMap containsKey() Methodto check whether a specific key exists in the HashMap.
Use a key of type String to get a value of type Integer:
Example
import
java.util.HashMap
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create a HashMap
HashMap
<
String
, Integer
primeNumbers
=
new
HashMap
<>
(
)
;
// Add a mapping to the HashMap
primeNumbers.
put
(
"Two"
,
2
)
;
primeNumbers.
put
(
"Three"
,
3
)
;
primeNumbers.
put
(
"Five"
,
5
)
;
System
.
out
.
println
(
"HashMap: "
primeNumbers
)
;
// Get the value
int
value
=
primeNumbers.
get
(
"Three"
)
;
System
.
out
.
println
(
"value for key Three: "
value
)
;
}
}
The output of the above program is:
HashMap: {Five=5, Two=2, Three=3}
key Three 对应的 value: 3
In the above example, we used the get() method to retrieve the value corresponding to the key Three.
Java HashMap