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 identifierdesignation: The role of the employee at that timemodifiedDate: 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:
- Group employees by
empId, and for each employee, keep only the record with the latestmodifiedDate. - 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()usesempIdas the key and keeps the Employee with the most recentmodifiedDate..values()returns only the latest Employee records.groupingBywithcounting()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.