map vs flatMap, groupingBy and Collectors
35 min · Intermediate
Most "write this with streams" interview questions end in a collector, and most stream theory questions start with map vs flatMap. Both topics come from Section 8 (Transforming Streams and Collectors); this lesson is the fast revision with the traps that cost marks.
Topics in this lesson
- map vs flatMap
- groupingBy with counting, mapping and summing
- toMap and the duplicate key exception
- partitioningBy, joining, and reduce vs collect
Interview questions this lesson answers
- What is the difference between map and flatMap?
- How does groupingBy work, and what does it return?
- What happens if toMap finds duplicate keys? How do you handle it?
- When would you use partitioningBy instead of groupingBy?
- What is the difference between reduce and collect?
- Write a stream that counts how often each word appears in a sentence.
- Your groupingBy output shows keys in a strange order. Is that a bug?
- What is a Collector?
- Which Collectors methods should every Java developer know?
- What does Collectors.toSet() return, and does it keep order?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.