🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this article, we will discuss five different ways to iterate over a HashMap in Java. Each method has its own advantages and use cases. We will cover the following methods:
- Iterate through a
HashMapEntrySet using an Iterator - Iterate through a
HashMapKeySet using an Iterator - Iterate through a
HashMapusing a For-each Loop - Iterate through a
HashMapusing Lambda Expressions - Loop through a
HashMapusing the Stream API
1. Iterate through a HashMap EntrySet using an Iterator
The entrySet method returns a set view of the mappings contained in the HashMap. Using an Iterator to traverse the entrySet allows you to access both the keys and values.
Example
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class IterateEntrySetUsingIterator {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
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());
}
}
}
Output:
Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Cherry, Value: 3
2. Iterate through a HashMap KeySet using an Iterator
The keySet method returns a set view of the keys contained in the HashMap. Using an Iterator to traverse the keySet allows you to access each key and then get the corresponding value.
Example
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class IterateKeySetUsingIterator {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
}
}
Output:
Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Cherry, Value: 3
3. Iterate through a HashMap using a For-each Loop
The enhanced for loop (for-each loop) provides a concise way to iterate over the entries of a HashMap.
Example
import java.util.HashMap;
import java.util.Map;
public class IterateUsingForEachLoop {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
Output:
Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Cherry, Value: 3
4. Iterating through a HashMap using Lambda Expressions
Java 8 introduced lambda expressions, which provide a more concise way to iterate over the entries of a HashMap.
Example
import java.util.HashMap;
import java.util.Map;
public class IterateUsingLambda {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
}
}
Output:
Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Cherry, Value: 3
5. Loop through a HashMap using the Stream API
Java 8 also introduced the Stream API, which can be used to process collections of objects in a functional style.
Example
import java.util.HashMap;
import java.util.Map;
public class IterateUsingStreamAPI {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
map.entrySet().stream()
.forEach(entry -> System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()));
}
}
Output:
Key: Apple, Value: 1
Key: Banana, Value: 2
Key: Cherry, Value: 3
Conclusion
These five methods provide different ways to iterate over a HashMap in Java, each with its own advantages:
- EntrySet with Iterator: Allows access to both keys and values with an iterator.
- KeySet with Iterator: Iterates over keys and retrieves values.
- For-each Loop: Simple and concise iteration over map entries.
- Lambda Expressions: Concise and functional style introduced in Java 8.
- Stream API: Functional programming approach for more complex operations.
Choose the method that best fits your needs based on the context and requirements of your application.
Hello, I want to translate this article into Chinese. Can I get translation authorization?
ReplyDelete