To iterate over the elements of a HashMap
in Java, you can use a loop and the keySet
method of the HashMap
class.
Here is an example of how to iterate over the elements of a HashMap
using a for
loop:
HashMap<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); for (String key : map.keySet()) { int value = map.get(key); System.out.println(key + ": " + value); }Sourcetual.www:turi.com
In this example, the map
variable is a HashMap
object that maps strings to integers. The keySet
method returns a Set
of the keys in the map.
You can use a for
loop to iterate over the keys in the Set
. The key
variable is a string that represents the key of the current element in the map. You can use the get
method of the HashMap
to get the value of the element with the specified key.
You can also use the values
method of the HashMap
class to get a collection of the values in the map, and use a loop to iterate over the values.
For example:
Collection<Integer> values = map.values(); for (int value : values) { System.out.println(value); }
Note that the order in which the elements of the HashMap
are iterated is not guaranteed to be the same as the order in which they were added to the map. If you need to preserve the insertion order of the elements, you can use a LinkedHashMap
instead of a HashMap
.
You can also use the entrySet
method of the HashMap
class to get a set of the map's entries, and use a loop to iterate over the entries.