Java program to iterate over a hashmap
In Java, you can iterate over a HashMap
using a for
loop or a for-each loop. Here are examples of both methods:
Method 1: Using a for loop
import java.util.HashMap; import java.util.Map; public class HashMapIteration { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("John", 25); map.put("Alice", 32); map.put("Bob", 18); map.put("Mary", 27); for (Map.Entry<String, Integer> entry : map.entrySet()) { String key = entry.getKey(); Integer value = entry.getValue(); System.out.println(key + " => " + value); } } }
In the above example, we define a HashMap
with String
keys and Integer
values. We use a for
loop to iterate over the key-value pairs of the HashMap
.
Inside the loop, we use the entrySet()
method of the HashMap
class to get a set of all the key-value pairs. We use the Map.Entry
interface to represent each key-value pair.
We store the key and value in separate variables and print them to the console using the System.out.println()
method.
After running the above code, the output would be:
John => 25 Alice => 32 Bob => 18 Mary => 27
Method 2: Using a for-each loop
import java.util.HashMap; import java.util.Map; public class HashMapIteration { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("John", 25); map.put("Alice", 32); map.put("Bob", 18); map.put("Mary", 27); for (String key : map.keySet()) { Integer value = map.get(key); System.out.println(key + " => " + value); } } }
In the above example, we define a HashMap
with String
keys and Integer
values. We use a for-each loop to iterate over the keys of the HashMap
.
Inside the loop, we use the keySet()
method of the HashMap
class to get a set of all the keys. We use the get()
method of the HashMap
class to get the value corresponding to the current key.
We store the key and value in separate variables and print them to the console using the System.out.println()
method.
After running the above code, the output would be:
John => 25 Alice => 32 Bob => 18 Mary => 27
This program iterates over the HashMap
and prints each key-value pair to the console using a for
loop and a for-each loop.