简体   繁体   English

使用 java 8 从比较元素的列表中删除

[英]Remove from list comparing elements using java 8

I am trying to use java8 streams to remove items from a list based elements of the object and confused on implementation.我正在尝试使用 java8 流从对象的基于列表的元素中删除项目,并且对实现感到困惑。 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 的对象,我想通过检查 startdate 和 enddate 是否为 eqaul 来将对象与列表中的其他对象进行比较,然后删除具有最少 id 的对象。

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:如果您的对象具有 (int id, Date startDate, Date endDate) 之类的属性,您可以使用一些容器类(如 Apache Commons 中的 Pair)将它们分组,然后在分组列表中找到最大 id:

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM