Java HashMap entrySet() Method
The entrySet() method returns a Set view of the mappings contained in the map.
The syntax of the entrySet() method is:
hashmap.entrySet()
**Note:** hashmap is an object of the HashMap class.
Parameter Description:
- None
Return Value
Returns a Set view of the mappings contained in this map.
**Note:** A Set view means all key/value pairs in the HashMap are treated as a set collection.
Example
The following example demonstrates the use of the entrySet() 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 set view of the mappings
System
.
out
.
println
(
"Set View: "
sites.
entrySet
(
)
)
;
}
}
The output of the above program is:
sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
Set View: [1=Google, 2=Runoob, 3=Taobao]
The entrySet() method can be used with a for-each loop to iterate over every mapping in the HashMap.
Example
import
java.util.HashMap
;
import
java.util.Map.Entry
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create a HashMap
HashMap
<
String
, Integer
numbers
=
new
HashMap
<>
(
)
;
numbers.
put
(
"One"
,
1
)
;
numbers.
put
(
"Two"
,
2
)
;
numbers.
put
(
"Three"
,
3
)
;
System
.
out
.
println
(
"HashMap: "
numbers
)
;
// Access each mapping in the HashMap
System
.
out
.
(
"Entries: "
)
;
// entrySet() returns a set view of all mappings in the HashMap
// for-each loop accesses each mapping in this view
for
(
Entry
<
String
, Integer
entry
:
numbers.
entrySet
(
)
)
{
System
.
out
.
(
entry
)
;
System
.
out
.
(
", "
)
;
}
}
}
The output of the above program is:
HashMap: {One=1, Two=2, Three=3}
Entries: One=1, Two=2, Three=3,
Java HashMap