3

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?

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
Andrew Mairose
  • 10,615
  • 12
  • 60
  • 102
  • It probably can, but how about this: how would you do this *without* the Stream API? How would you want to go about doing something like this? – Makoto Jul 27 '15 at 16:17
  • How is this Question different than [the one you posted an hour earlier](http://stackoverflow.com/q/31657036/642706)? Multiple good answers there showed you how to use steams to filter to get latest date. – Basil Bourque Jul 27 '15 at 16:40
  • @BasilBourque, the question earlier was how to get the object with a max date from a list. This question is more complex. – Andrew Mairose Jul 27 '15 at 16:43

1 Answers1

7

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)));
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334