✅ 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 aCollection<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
| Approach | Code |
|---|---|
| For-each loop | for (V value : map.values()) |
| Iterator | Iterator<V> it = map.values().iterator() |
| Lambda | map.values().forEach(...) |
| Stream | map.values().stream()... |