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 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>, 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?
解决方案
You can chain several collectors to get what you want:
import static java.util.stream.Collectors.*;
List list = ...
Map logs = list.stream()
.collect(groupingBy(Log::getContact,
collectingAndThen(maxBy(Comparator.comparing(Log::getLastUpdated)), Optional::get)));