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.

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay