Java – a good way to filter lists sorted by attribute and by date

I have very simple things to do. I have such a list of personnel:

[{
    name: John,date: 01-01-2018,attend: true
},{
    name: Adam,attend: false
},date: 01-02-2018,{
    name: JOHN,attend: false
}]

The result of this array should be: Adam (true), John (false)

Therefore, I need to return the user's latest entry list. In this case, John first confirms that he is participating, and then he changes his mind and tells him that he is not participating, so I will return his last entry (please note that sometimes it writes John, sometimes John, but it is the same person, which is a tricky part)

My question is what is the best way to filter out this list. I'm considering applying the "uniqueness of attribute Java stream", but first I need to order people by date descending order and name (uppercase / lowercase), and then I need some way to take the latest entry

Anyone knows what is the best way?

Solution

You can use collectors Tomap performs the same operation:

List<Person> finalList = new ArrayList<>(people.stream()
        .collect(Collectors.toMap(a -> a.getName().toLowerCase(),// name in lowercase as the key of the map (uniqueness)
                Function.identity(),// corresponding Person as value
                (person,person2) -> person.getDate().isAfter(person2.getDate()) ? person : person2)) // merge in case of same name based on which date is after the other
        .values()); // fetch the values

Note: the smallest person class is assumed above

class Person {
    String name;
    java.time.LocalDate date;
    boolean attend;
    // getters and setters
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>