intermediateFunctional Programming
How does Collectors.groupingBy() work in the Stream API? Give an example.
groupingBy() collects stream elements into a Map, where a classifier function you supply determines the key for each element and all elements mapping to the same key are collected into a List under that key by default. For example, employees.stream().collect(Collectors.groupingBy(Employee::getDepartment)) produces a Map<String, List<Employee>> grouping employees by department; a second argument (a downstream collector) can further reduce each group, e.g. to a count or an average.
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