Stream from Map: entrySet(), keySet(), values()
You'll learn how to convert Maps into streams to process their entries, keys, or values using declarative stream operations.
The Core Idea
Maps don't implement Collection, so they don't have a direct stream() method. However, you can create streams from different "views" of a map:
entrySet()returns a set of key-value pairs (Map.Entry<K, V>)keySet()returns a set of just the keysvalues()returns a collection of just the values
Each of these collections does support stream(), giving you different perspectives on your map data.
Think of It Like This
Imagine a library catalog map where book titles are keys and authors are values. You might want to:
- Browse all entries (title + author pairs)
- Just list all titles (keys)
- Just list all authors (values)
Each view gives you a different stream to work with.
The Three Methods in Action
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 92);
// Stream of entries (key-value pairs)
scores.entrySet().stream()
.forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue()));
// Stream of keys only
scores.keySet().stream()
.forEach(name -> System.out.println(name));
// Stream of values only
scores.values().stream()
.forEach(score -> System.out.println(score));
Use entrySet() when you need both key and value together, keySet() when you only care about keys, and values() when you only need the values.
Key Takeaway: Maps become streamable through their collection views—entrySet().stream() for full entries, keySet().stream() for keys only, and values().stream() for values only.