beginnerFunctional Programming
What does the Stream collect() method do, and what's the difference between collect() and forEach()?
collect() is a terminal operation that gathers the stream's elements into a final result — a List, Set, Map, or a custom accumulation — using a Collector like Collectors.toList() or Collectors.joining(). forEach() is also terminal but performs a side-effecting action (like printing) per element and returns nothing; use collect() when you need a data structure back, forEach() when you just need to act on each element.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response