I am trying to use java8 streams to remove items from a list based elements of the object and confused on implementation. I have an object with startdate,enddate and id and I want to compare objects with other objects in the list by checking if the startdate and enddate are eqaul then remove the object which has the least ids.
startdate enddate Id
--------- --------- -----
01-01-2018 01-05-2018 1
01-01-2018 01-05-2018 2
01-01-2018 01-05-2018 3
01-20-2018 01-25-2018 4
01-20-2018 01-25-2018 5
Then the resulting list will be
startdate enddate Id
--------- --------- -----
01-01-2018 01-05-2018 3
01-20-2018 01-25-2018 5
If your objects have properties like (int id, Date startDate, Date endDate), you can group by them using some container class like Pair from Apache Commons, then find max id on grouped lists:
originalObjectsList.stream()
.collect(groupingBy(t -> new Pair(t.startDate, t.endDate)))
.values()
.stream()
.map(t -> t.stream().max(Comparator.comparingInt(a -> a.id)).get())
.collect(Collectors.toList())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.