HashMap and iterate over its entries in java. involves several approaches depending on what you need to accomplish. Here, I’ll demonstrate three common methods . HashMap and iterate over its entries in java:
1. Iterating using entrySet()
This method is efficient because it accesses both the key and value in each iteration.
java import java.util.; public class HashMapIterationProgram { public static void main(String[] args) { // Creating a HashMap Map<String, Integer> map = new HashMap<>(); map.put("John", 215); map.put("Jane", 310); map.put("Doe", 410); // Iterating over the Hash-Map using entry-Set() for (Map.Entry<String, Integer> entry : map.entrySet()) { String key = entry.getKey(); Integer value = entry.getValue(); System.out.println(key + " => " + value); } } }
Explanation:
`entrySet()` provides a set containing all mappings stored within the map.
– We iterate over each Map.Entry<String, Integer> in the set obtained from entrySet().
– For each entry, getKey() retrieves the key, and getValue() retrieves the corresponding value.
– We print each key-value pair.
2. Iterating using keySet()
This approach allows iterating over keys and then fetching corresponding values using get(key).
java import java.util.; public class HashMapIterationProgram { public static void main(String[] args) { // Creating a HashMap Map<String, Integer> map = new HashMap<>(); map.put("rahul", 251); map.put("shubham", 301); map.put("Gaurav", 410); // Iterating over the HashMap using keySet() for (String key : map.keySet()) { Integer value = map.get(key); System.out.println(key + " ===> " + value); } } }
Explanation:
– keySet() returns a set view of the keys contained in the map.
– We iterate over each key using the enhanced for loop.
– For each key, get(key) retrieves the corresponding value.
– We print each key-value pair.
3. Iterating using Java 8’s forEach() with lambda expressions
This method provides a concise way to iterate over the entries.
java import java.util.; public class HashMapIterationProgram{ public static void main(String[] args) { // Creating a HashMap Map<String, Integer> map = new HashMap<>(); map.put("Laptop", 2500); map.put("Mouse", 3000); map.put("Charger", 4000); // Iterat over the Hash-Map using forEach() and lambda-expression map.forEach((key, value) -> { System.out.println(key + " => " + value); }); } }
Explanation:
– forEach() is a new method in Java 8 that accepts a lambda expression taking two parameters (key and value).
– The lambda expression System.out.println(key + ” => ” + value); is applied to each key-value pair in the map .
Summary
– entrySet(): Preferred when you need both keys and values.
– keySet(): Useful if you only need keys and can fetch values using get(key).
– forEach(): Concise for simple iterations in Java 8 and later versions.