Posted on: April 21, 2025 Posted by: rahulgite Comments: 0

Given a list of Employee objects, where an employee can appear multiple times due to designation changes, how can we use Java Streams to count the number of unique employees based on their most recent designation?

Each Employee object contains:

  • empId: Unique employee identifier
  • designation: The role of the employee at that time
  • modifiedDate: The timestamp when the record was last updated

We want to ensure that for each employee, only the most recent record (based on modifiedDate) is considered for counting.

Answer:

We can solve this using Java Streams by following these steps:

  1. Group employees by empId, and for each employee, keep only the record with the latest modifiedDate.
  2. From these latest records, count how many employees are in each designation.

✅ Java Stream Code:

Map<String, Long> designationCounts = employees.stream()
    // Step 1: Group by empId and keep the latest record based on modifiedDate
    .collect(Collectors.toMap(
        Employee::getEmpId,
        e -> e,
        (e1, e2) -> e1.getModifiedDate().isAfter(e2.getModifiedDate()) ? e1 : e2
    ))
    // Step 2: Stream the latest records and count by designation
    .values().stream()
    .collect(Collectors.groupingBy(
        Employee::getDesignation,
        Collectors.counting()
    ));

🧠 Explanation:

  • toMap() uses empId as the key and keeps the Employee with the most recent modifiedDate.
  • .values() returns only the latest Employee records.
  • groupingBy with counting() gives you the final count per designation.

📝 Example:

List<Employee> employees = List.of(
    new Employee(1L, "Dev", LocalDateTime.parse("2024-01-01T10:00:00")),
    new Employee(1L, "Lead", LocalDateTime.parse("2024-02-01T10:00:00")),
    new Employee(2L, "Dev", LocalDateTime.parse("2024-03-01T10:00:00")),
    new Employee(3L, "Manager", LocalDateTime.parse("2024-04-01T10:00:00"))
);

Output:

{Lead=1, Dev=1, Manager=1}

This approach ensures you’re counting employees by their most recent designation only.

Leave a Comment