A HashMap in Java is a collection that stores key-value pairs. It’s widely used for fast data retrieval based on keys. In this tutorial by The Coding College, we’ll explore multiple ways to iterate through a HashMap effectively.
Example HashMap Setup
Let’s start with a simple example HashMap to use in all our demonstrations:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> people = new HashMap<>();
people.put("Alice", 25);
people.put("Bob", 30);
people.put("Charlie", 35);
// Use the examples below to loop through this HashMap.
}
}
Method 1: Using a For-Each Loop for EntrySet
The entrySet()
method returns a set of key-value pairs, which can be iterated with a for-each loop.
Example Code
for (HashMap.Entry<String, Integer> entry : people.entrySet()) {
System.out.println("Name: " + entry.getKey() + ", Age: " + entry.getValue());
}
Output:
Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35
Method 2: Using a For-Each Loop for Keys and Values
You can iterate through the keys and fetch corresponding values using keySet()
.
Example Code
for (String name : people.keySet()) {
System.out.println("Name: " + name + ", Age: " + people.get(name));
}
Output:
Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35
Method 3: Using an Iterator
An Iterator
provides another way to traverse the entries in the HashMap.
Example Code
import java.util.Iterator;
import java.util.Map;
Iterator<Map.Entry<String, Integer>> iterator = people.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println("Name: " + entry.getKey() + ", Age: " + entry.getValue());
}
Output:
Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35
Method 4: Using Java Streams
Introduced in Java 8, Streams offer a modern and concise way to loop through a HashMap.
Example Code
people.forEach((name, age) -> System.out.println("Name: " + name + ", Age: " + age));
Output:
Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35
Method 5: Using a While Loop
If you prefer a while
loop for better control over the iteration, you can combine it with an Iterator
.
Example Code
Iterator<String> keyIterator = people.keySet().iterator();
while (keyIterator.hasNext()) {
String name = keyIterator.next();
System.out.println("Name: " + name + ", Age: " + people.get(name));
}
Output:
Name: Alice, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35
Method 6: Iterating Over Values Only
To iterate over values alone, use the values()
method.
Example Code
for (Integer age : people.values()) {
System.out.println("Age: " + age);
}
Output:
Age: 25
Age: 30
Age: 35
Best Practices
- Choose the Right Method:
- Use
entrySet()
for both keys and values. - Use
keySet()
if you only need keys or need to fetch values dynamically. - Use
forEach
for modern, concise code.
- Use
- Thread Safety: Use
ConcurrentHashMap
instead ofHashMap
in multithreaded environments to avoidConcurrentModificationException
. - Performance: Iterating over
entrySet
is generally faster than fetching values repeatedly withkeySet
.
Conclusion
Java offers a variety of ways to loop through a HashMap, making it flexible for different use cases. Choose the method that best suits your specific requirements.
For more in-depth tutorials, visit The Coding College and take your coding skills to the next level!