Stream Group By Interview Questions

Akshay Aryan
2 min readApr 6, 2024

Stream` API, are crucial for efficiently organizing and manipulating collections based on certain attributes. Here are some interview questions related to using `group by` operations with Java Streams:

Q1 -> How do you group a list of objects by an attribute in Java using streams?

Map<String, List<Employee>> employeesByDepartment = 
employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));

2. Write a Java Stream expression that groups a list of strings by their lengths.

Map<Integer, List<String>> stringsByLength = 
strings.stream()
.collect(Collectors.groupingBy(String::length));

3. How can you achieve multi-level grouping with Java Streams?

Multi-level grouping in Java Streams can be achieved by passing a `groupingBy` collector as the downstream collector to another `groupingBy` collector. This allows for grouping on two levels, first by one attribute and then by another. For example, if you want to group employees by department and then by gender, you could do:

Map<String, Map<Gender, List<Employee>>> byDeptThenGender = 
employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.groupingBy(Employee::getGender)));

4. How to use `groupingBy` to count…

--

--

Akshay Aryan

Cultivating a passion for technology and delving into intriguing, lesser-known tech facts.