DEV Community

realNameHidden
realNameHidden

Posted on

3 1 1 1 1

Java Stream Scenario Based Interview Question

You have a list of employees with fields like name, age, and department. Write a code snippet to group employees by department using Java Streams.

Solution

import java.util.*;
import java.util.stream.Collectors;

class Employee {
    private String name;
    private int age;
    private String department;

    // Constructor
    public Employee(String name, int age, String department) {
        this.name = name;
        this.age = age;
        this.department = department;
    }

    // Getters
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getDepartment() {
        return department;
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

public class StreamExample {
    public static void main(String[] args) {
        // Create a list of employees
        List<Employee> employees = Arrays.asList(
                new Employee("John", 25, "HR"),
                new Employee("Jane", 28, "Finance"),
                new Employee("Jake", 22, "HR"),
                new Employee("Jill", 35, "Finance"),
                new Employee("Joe", 29, "IT")
        );

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

        // Print the grouped employees
        employeesByDepartment.forEach((department, empList) -> {
            System.out.println(department + ": " + empList);
        });
    }
}

Enter fullscreen mode Exit fullscreen mode

Explanation
stream(): Creates a stream from the list of employees.

Collectors.groupingBy(Employee::getDepartment):
Groups employees by the value of their department field.
Returns a Map>, where the key is the department, and the value is a list of employees in that department.

forEach():
Iterates over the Map and prints the department name and the list of employees.

Output
For the given list:

[
    new Employee("John", 25, "HR"),
    new Employee("Jane", 28, "Finance"),
    new Employee("Jake", 22, "HR"),
    new Employee("Jill", 35, "Finance"),
    new Employee("Joe", 29, "IT")
]

Enter fullscreen mode Exit fullscreen mode

The output will be:

HR: [John (25), Jake (22)]
Finance: [Jane (28), Jill (35)]
IT: [Joe (29)]

Enter fullscreen mode Exit fullscreen mode

Edge Cases
Empty List: If the list is empty, the resulting map will also be empty.

All Employees in the Same Department: The map will have a single key with all employees grouped under it.

[
    new Employee("John", 25, "HR"),
    new Employee("Jane", 28, "HR"),
    new Employee("Jake", 22, "HR")
]

Enter fullscreen mode Exit fullscreen mode

Output:

HR: [John (25), Jane (28), Jake (22)]

Enter fullscreen mode Exit fullscreen mode

Key Takeaways
Collectors.groupingBy() is a powerful tool for grouping data in streams.

Use toString() to customize how objects appear in the output.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs