Java.Collections.How to iterate over all values ​​in a Map?

✅ 1. Enhanced for loop using map.values()

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

for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}
  • map.values() returns a Collection<V> of all the values.
  • This is the simplest and most common way.

✅ 2. Using an Iterator

Iterator<Integer> iterator = map.values().iterator();
while (iterator.hasNext()) {
    Integer value = iterator.next();
    System.out.println("Value = " + value);
}

Useful if you want to remove values during iteration (with iterator.remove()).

✅ 3. Java 8+ forEach() with lambda

map.values().forEach(value -> System.out.println("Value = " + value));
  • A concise, functional-style approach.

✅ 4. Stream API (for filtering or processing)

map.values().stream()
   .filter(value -> value > 1)
   .forEach(System.out::println);
  • Great for more advanced tasks like filtering, mapping, collecting, etc.

🧠 TL;DR

ApproachCode
For-each loopfor (V value : map.values())
IteratorIterator<V> it = map.values().iterator()
Lambdamap.values().forEach(...)
Streammap.values().stream()...
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.