Dan Dan - 6 days ago 4
Java Question

Java and max value issue

I am working with a

List
of
Person
objects. I am trying to quickly identify and return all
Person
's with the maximum date.

For example:

Persons:[
{
id: 1
submitDate: 2010-01-01
name : john Smith
},
{
id: 1
submitDate: 2011-01-01
name : john Smith
},
{
id: 2
submitDate: 2011-01-02
name : jason Doe
},
{
id: 1
submitDate: 2012-01-01
name : john Smith
},
{
id: 1
submitDate: 2013-01-01
name : john Smith
},
{
id: 2
submitDate: 2013-01-02
name : jason Doe
}
]


I am looking for a way, in Java, to return the following (Max
submitDate
value):

Persons: [
{
id: 1
submitDate: 2013-01-01
name : john Smith
},
{
id: 2
submitDate: 2013-01-02
name : jason Doe
}
]


Any thoughts on how to best achieve this?

========================================================================
I've tried:

List<Person> personList = Lists.newArrayList();
getPersonList().stream()
.map(this.setSource)
.max(Comparator.comparing(Person::getSubmitDate))
.map(personList::add);


However it returns a single
Person
record, Not the max submitDate for each
Person

Answer
    List<Person> persons = ...
    List<Person> resultList = new ArrayList<>();
    Map<Integer, List<Person>> personsBySubmitDate =
            persons.stream().collect(Collectors.groupingBy(person -> person.getId());

    for (Map.Entry<Integer, List<Person>> entry : personsBySubmitDate.entrySet()) {
        Person currentPerson = entry.getValue()
                                    .stream()
                                    .max(Comparator.comparing(Person::getSubmitDate))
                                    .orElse(null);
        resultList.add(currentPerson);
    }

It should be O(n).