Java HashMap values() Method
The values() method returns a Set view of all values in the map.
The syntax of the values() method is:
hashmap.values()
**Note:** hashmap is an object of the HashMap class.
Parameter Description:
- None
Return Value
Returns a collection view consisting of all value values in the HashMap.
Example
The following example demonstrates the use of the values() 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
)
;
// Return the view consisting of all values
System
.
out
.
println
(
"Values: "
sites.
values
(
)
)
;
}
}
The output of the above program is:
sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
Values: [Google, Runoob, Taobao]
The values() method can be used with a for-each loop to iterate over all values in the HashMap.
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
)
;
// Access all values in the HashMap
System
.
out
.
(
"Values: "
)
;
// values() returns a view of all values
// for-each loop can access each value from the view
for
(
String
value
:
sites.
values
(
)
)
{
// Output each value
System
.
out
.
(
value
", "
)
;
}
}
}
The output of the above program is:
sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
Values: Google, Runoob, Taobao,
Java HashMap