I have list of object array with employee details. I need to find the duplicate employee based on the employee ID and remove the details of old emplyee using create date.
I need to do this using either Google Guava or Apache Commons Collection.
I have list of object array with employee details. I need to find the duplicate employee based on the employee ID and remove the details of old emplyee using create date.
I need to do this using either Google Guava or Apache Commons Collection.
I don't think that you need to use Guava or Apache Collections for this.
You can simply create a map of employee ID to employee details, and then update this to take the most recently-created employee details:
LinkedHashMap<EmployeeId, EmployeeDetails> map = new LinkedHashMap<>();
for (EmployeeDetails details : list) {
if (!map.containsKey(details.getEmployeeId())) {
map.put(details.getEmployeeId(), details);
} else {
EmployeeDetails previous = map.get(details.getEmployeeId());
if (previous.getCreatedDate().before(details.getCreatedDate())) {
map.put(details.getEmployeeId(), details);
}
}
}
List<EmployeeDetails> deduplicated = new ArrayList<>(map.values());
If you are not forced to use Google Guava or Apache Commons Collection, just Java 8 (using Integer as id, but could be anything):
Map<Integer, List<Employee>> employeeMap = employees.stream()
.collect(Collectors.groupingBy(Employee::getId));
List<Employee> filtered = collect.entrySet().stream()
.map(e -> Collections.max(e.getValue(), Comparator.comparing(Employee::getCreatedDate)))
.collect(Collectors.toList());
If you need to use Guava this should work:
Map<Integer, Collection<Employee>> employeeMap = Multimaps.index(employees, Employee::getId).asMap();
Collection<Employee> filtered = Maps.transformValues(employeeMap, l -> Ordering.from(Comparator.comparing(Employee::getCreatedDate)).max(l)).values();