📅  最后修改于: 2023-12-03 15:31:30.409000             🧑  作者: Mango
HashMap
is a hash table based implementation of Map
interface in Java. It uses a hash function to calculate the index of elements and stores them in a table. The EntrySet
of a HashMap
represents a set of key-value pairs stored in the HashMap
. In this article, we will discuss the EntrySet
in detail.
The EntrySet
of a HashMap
contains objects of the Map.Entry
class. The Map.Entry
interface is used to represent a key-value pair in a Map
. The EntrySet
provides a way to access the entries of a HashMap
in a forward manner. The EntrySet
interface contains methods to get a Set
of keys, values or entries.
Here is an example of getting an EntrySet
from a HashMap
:
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "John");
map.put(2, "Peter");
map.put(3, "Sarah");
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
In the above example, we have created a HashMap
and added some key-value pairs to it. Then we have called the entrySet()
method to get the EntrySet
of the HashMap
. The entrySet()
method returns a Set
of the Map.Entry
type.
We can iterate over the EntrySet
of a HashMap
using a for-each
loop. The EntrySet
provides a way to access the key-value pairs of a HashMap
. Here is an example:
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "John");
map.put(2, "Peter");
map.put(3, "Sarah");
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
for (Map.Entry<Integer, String> entry : entrySet) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
In the above example, we have created a HashMap
and added some key-value pairs to it. Then we have called the entrySet()
method to get the EntrySet
of the HashMap
. We have iterated over the EntrySet
using a for-each
loop and printed the key-value pairs.
The EntrySet
of a HashMap
provides a way to access the key-value pairs stored in the HashMap
. We can use the entrySet()
method to get the EntrySet
. The EntrySet
contains objects of the Map.Entry
class. We can iterate over the EntrySet
using a for-each
loop to access the key-value pairs.