Introduce Java How To Loop Through a HashMap and give examples
In Java, a HashMap
is a part of the Java Collections Framework and is used to store key-value pairs. Looping through a HashMap
can be done in several ways, depending on what you want to achieve. Below are some common methods to iterate through a HashMap
along with examples.
for-each
Loop with entrySet()
The entrySet()
method returns a set view of the mappings contained in the map. You can then use a for-each loop to iterate through the entries.
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
// Loop through the HashMap using entrySet()
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
for-each
Loop with keySet()
You can also iterate through the keys of the HashMap
using the keySet()
method and then retrieve the corresponding values.
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
// Loop through the HashMap using keySet()
for (String key : map.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
}
}
forEach
Method (Java 8 and above)Java 8 introduced the forEach
method, which allows you to iterate through the HashMap
using a lambda expression.
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
// Loop through the HashMap using forEach
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
});
}
}
You can also use an Iterator
to loop through the HashMap
. This is useful if you need to remove entries while iterating.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
// Loop through the HashMap using an Iterator
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());
}
}
}
These are some of the common ways to loop through a HashMap
in Java. Depending on your specific needs (e.g., whether you need to modify the map during iteration), you can choose the method that best suits your requirements.