Andrew Mairose
Andrew Mairose

Reputation: 10995

Use Java 8 Stream API to filter objects based on an ID and Date

I have a Contact class, for which each instance has a unique contactId.

public class Contact {
    private Long contactId;

    ... other variables, getters, setters, etc ...
}

And a Log class that details an action performed by a Contact on a certain lastUpdated date.

public class Log {
    private Contact contact;
    private Date lastUpdated;
    private String action;

    ... other variables, getters, setters, etc ...
}

Now, in my code I have a List<Log> that can contain multiple Log instances for a single Contact. I would like to filter the list to include only one Log instance for each Contact, based on the lastUpdated variable in the Log object. The resulting list should contain the newest Log instance for each Contact.

I could do this by creating a Map<Contact, List<Log>>, then looping through and getting the Log instance with max lastUpdated variable for each Contact, but this seems like it could be done much simpler with the Java 8 Stream API.

How would one accomplish this using the Java 8 Stream API?

Upvotes: 3

Views: 3260

Answers (1)

Tagir Valeev
Tagir Valeev

Reputation: 100269

You can chain several collectors to get what you want:

import static java.util.stream.Collectors.*;

List<Log> list = ...
Map<Contact, Log> logs = list.stream()
    .collect(groupingBy(Log::getContact,
        collectingAndThen(maxBy(Comparator.comparing(Log::getLastUpdated)), Optional::get)));

Upvotes: 7

Related Questions