Introduction
- In this blog, we will explore different ways to iterate over a map in Java, discussing various techniques and code examples. Let's dive in!
1. Iterating using a for-each loop
- The for-each loop provides a simple way to iterate over a map. The key-value pairs of the map can be accessed by using the entrySet() method. Here's an illustration:
import java.util.HashMap;
import java.util.Map;
public class IterationWithFor {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 15);
map.put("Orange", 5);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
2. Iterating using iterators
- Using iterators provides more control over the iteration process. We can obtain an iterator using the entrySet().iterator() method and then iterate using a while loop. Here's an illustration:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class IterationWithIterator {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 5);
map.put("Orange", 8);
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " entry.getValue());
}
}
}
3. Iterating using Java 8 Stream API
- We can iterate over a map using streams and lambdas now that Java 8 includes the Stream API. Here's an illustration:
import java.util.HashMap;
import java.util.Map;
public class IterationWithStream {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 5);
map.put("Orange", 8);
map.entrySet().stream()
.forEach(entry -> {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
});
}
}
4. Iterating over keys or values:
- you can also iterate over the keys or values of a map independently, you can use the keySet() or values() methods, respectively. Here are examples for both cases:
import java.util.HashMap;
import java.util.Map;
public class IterationOnKeyValue {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 15);
map.put("Orange", 5);
for (String key : map.keySet()) {
System.out.println("Key: " + key);
}
for (Integer value : map.values()) {
System.out.println("Value: " + value);
}
}
}
Conclusion
- In this blog, we explored different ways to iterate on a map: using a for-each loop, iterators, Java 8 Stream API, and iterating over keys or values directly. Each approach has its advantages and can be chosen based on specific requirements.