🔥 Launch Offer: Interview Preparation Bundle @ ₹2,499 ₹9,999 • 75% OFF. Offer expires in 🔥 Launch Offer: Interview Preparation Bundle @ ₹2,499 ₹9,999 • 75% OFF. Offer expires in Interview Preparation Bundle @ ₹2,499 ₹9,999

00:00:00 Get Bundle
home / practice / group-employees-by-department-streams
easy Java 8

Group employees by department (Streams)

You are given a list of Employee objects with name and department. Return a Map<String, List<Employee>> grouped by department using the Stream API — no manual loops.

Example

Input:  [Asha→Eng, Ravi→HR, Meera→Eng]
Output: Eng → [Asha, Meera], HR → [Ravi]

Constraints

  • Use Collectors.groupingBy.
  • Null department should map to "UNKNOWN".

Starter code

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

record Employee(String name, String department) {}

public class GroupByDept {
    public static Map<String, List<Employee>> group(List<Employee> employees) {
        // TODO: groupingBy
        return Map.of();
    }

    public static void main(String[] args) {
        List<Employee> list = List.of(
            new Employee("Asha", "Eng"),
            new Employee("Ravi", "HR"),
            new Employee("Meera", "Eng")
        );
        System.out.println(group(list));
    }
}

Solution

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

record Employee(String name, String department) {}

public class GroupByDept {
    public static Map<String, List<Employee>> group(List<Employee> employees) {
        return employees.stream()
            .collect(Collectors.groupingBy(
                e -> e.department() == null ? "UNKNOWN" : e.department()
            ));
    }

    public static void main(String[] args) {
        List<Employee> list = List.of(
            new Employee("Asha", "Eng"),
            new Employee("Ravi", "HR"),
            new Employee("Meera", "Eng")
        );
        System.out.println(group(list));
    }
}