Iterate over a HashMap in Java - Four different ways
In this section, we will show you 4 different ways to iterate through a HashMap in Java.
- Using Advanced for loop
- Iterating over keys or values using keySet() and values() methods
- Using Iterator
- Using Java 8 forEach
1. Using Advanced for loop
// create hashmap
Map<Integer, String> lanuages = new HashMap<>();
// add 5 different key/values to map
lanuages.put(1, "Java");
lanuages.put(2, "Scala");
lanuages.put(3, "Kotlin");
lanuages.put(4, "Go");
lanuages.put(5, "Python");
// iterate via Advanced for loop
System.out.println("\n==> Advance For Loop Example..");
for (Map.Entry<Integer, String> entry : lanuages.entrySet()) {
System.out.println(entry);
}
2. Iterating over keys or values using keySet() and values() methods
// create hashmap
Map<Integer, String> lanuages = new HashMap<>();
// add 5 different key/values to map
lanuages.put(1, "Java");
lanuages.put(2, "Scala");
lanuages.put(3, "Kotlin");
lanuages.put(4, "Go");
lanuages.put(5, "Python");
// Iterating over keys or values using keySet() and values() methods
System.out.println("\n==> Iterating over keys or values using keySet() and values() methods...");
// using keySet() for iteration over keys
for (Integer key : lanuages.keySet())
System.out.println(key);
// using values() for iteration over keys
for (String value : lanuages.values())
System.out.println(value);
3. Using Iterator
// create hashmap
Map<Integer, String> lanuages = new HashMap<>();
// add 5 different key/values to map
lanuages.put(1, "Java");
lanuages.put(2, "Scala");
lanuages.put(3, "Kotlin");
lanuages.put(4, "Go");
lanuages.put(5, "Python");
// iterate via "iterator loop"
System.out.println("\n==> Iterator Example...");
Iterator<Map.Entry<Integer, String>> it = lanuages.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> pair = (Map.Entry<Integer, String>) it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
4. Using Java 8 forEach
// create hashmap
Map<Integer, String> lanuages = new HashMap<>();
// add 5 different key/values to map
lanuages.put(1, "Java");
lanuages.put(2, "Scala");
lanuages.put(3, "Kotlin");
lanuages.put(4, "Go");
lanuages.put(5, "Python");
// iterate via "iterator loop"
System.out.println("\n==> Iterator Example...");
Iterator<Map.Entry<Integer, String>> it = lanuages.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> pair = (Map.Entry<Integer, String>) it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
More Interesting topics,