Java.Core.How to iterate over all keys in a Map?

Iterating over all keys in a Map is very common, and Java makes it super easy.

Here are 4 common ways to do it with a HashMap (or any Map<K, V>):

✅ 1. Enhanced for loop

The cleanest and most readable way:

Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);

for (String key : map.keySet()) {
    System.out.println("Key = " + key);
}

🧠 map.keySet() returns a Set<K> view of the keys.


✅ 2. Using an Iterator

If you want more control (e.g., to remove elements while iterating):

Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
    String key = iterator.next();
    System.out.println("Key = " + key);
}

✅ 3. Java 8+ forEach() with lambda

Sleek and functional style:

map.keySet().forEach(key -> System.out.println("Key = " + key));

✅ 4. Stream API (if doing something complex)

This is overkill for just printing, but great for filtering, mapping, etc.:

map.keySet().stream()
   .filter(k -> k.startsWith("a"))
   .forEach(System.out::println);

🧠 Bonus: Iterating over entries (keys and values)

If you ever want both key and value:

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
This entry was posted in Без рубрики. Bookmark the permalink.