🎓 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Hello, I want to translate this article into Chinese. Can I get translation authorization?
ReplyDelete