Java 8 Streams reduce remove duplicates keeping the most recent entry

Nestor Milyaev :

I have a Java bean, like

class EmployeeContract {
    Long id;
    Date date;
    getter/setter
}

If a have a long list of these, in which we have duplicates by id but with different date, such as:

1, 2015/07/07
1, 2018/07/08
2, 2015/07/08
2, 2018/07/09

How can I reduce such a list keeping only the entries with the most recent date, such as:

1, 2018/07/08
2, 2018/07/09

? Preferably using Java 8...

I've started with something like:

contract.stream()
         .collect(Collectors.groupingBy(EmployeeContract::getId, Collectors.mapping(EmployeeContract::getId, Collectors.toList())))
                    .entrySet().stream().findFirst();

That gives me the mapping within individual groups, but I'm stuck as to how to collect that into a result list - my streams are not too strong I'm afraid...

Eugene :

Well, I am just going to put my comment here in the shape of an answer:

 yourList.stream()
         .collect(Collectors.toMap(
                  EmployeeContract::getId,
                  Function.identity(),
                  BinaryOperator.maxBy(Comparator.comparing(EmployeeContract::getDate)))
            )
         .values();

This will give you a Collection instead of a List, if you really care about this.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73564&siteId=1