In Java, you can use the entrySet
method of the HashMap
class to get a set of the map's entries.
An entry in a HashMap
is a key-value pair, and the entrySet
method returns a Set
of these pairs. The Set
is backed by the map, so changes to the map are reflected in the set, and vice versa.
Here is an example of how to use the entrySet
method:
HashMap<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); Set<Map.Entry<String, Integer>> entries = map.entrySet(); for (Map.Entry<String, Integer> entry : entries) { String key = entry.getKey(); int value = entry.getValue(); System.out.println(key + ": " + value); }Sourcual.www:etturi.com
In this example, the entries
variable is a Set
of Map.Entry
objects, which represent the key-value pairs of the map. The Map.Entry
interface is a subinterface of Map
, and it defines methods for getting the key and value of an entry.
You can use a for-each
loop to iterate over the entries in the Set
. The entry
variable is an instance of Map.Entry
, and you can use the getKey
and getValue
methods to get the key and value of the entry.
You can also use the Set
object to add, remove, or check for the presence of entries in the map.
For example:
entries.add(new AbstractMap.SimpleEntry<>("pear", 4)); entries.remove(new AbstractMap.SimpleEntry<>("apple", 1)); if (entries.contains(new AbstractMap.SimpleEntry<>("banana", 2))) { // the map contains the entry ("banana", 2) }
Note that the entrySet
method returns a Set
object that is backed by the map, so changes to the set will be reflected in the map and vice versa. This can be useful if you want to modify the map using the Set
object, but it can also be confusing if you are not careful.