Wednesday, January 22, 2025
HomeProgrammingHow to iterate any Map in Java

How to iterate any Map in Java

In Java, you can iterate over a Map using several methods to access its keys, values, or key-value pairs. The most common ways include:

1. Using for-each loop and entrySet():
This is the most common method to iterate over both keys and values.
java
Map<String, Integer> map = new HashMap<>();
map.put(“A”, 1);
map.put(“B”, 2);

See also  What regular expression can be used to reformat a US phone number?

for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(“Key: ” + entry.getKey() + “, Value: ” + entry.getValue());
}

2. Using for-each loop and keySet():
Iterate over keys and then fetch values.
java
for (String key : map.keySet()) {
System.out.println(“Key: ” + key + “, Value: ” + map.get(key));
}

See also  Understanding Aliasing in Java

3. Using for-each loop and values():
Iterate over values only.
java
for (Integer value : map.values()) {
System.out.println(“Value: ” + value);
}

4. Using Iterator:
Iterate using an Iterator for entrySet().
java
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());
}

See also  String Comparison in SQL

These methods allow efficient access to the elements of a Map in Java.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x