如何通过使用Java流比较多个嵌套对象中的值来删除重复项

如何通过使用Java流比较多个嵌套对象中的值来删除重复项,java,java-stream,Java,Java Stream,我有一个包含多个嵌套对象的复杂对象列表。我需要比较复杂对象中的4个元素,以确定它是否重复并删除它。 这是要比较重复项的复杂对象和元素 - Segment * Billing (string) - element to compare for duplication * Origin (object) number (int) - element to compare for duplication string1

我有一个包含多个嵌套对象的复杂对象列表。我需要比较复杂对象中的4个元素,以确定它是否重复并删除它。 这是要比较重复项的复杂对象和元素

 - Segment       
   * Billing (string) - element to compare for duplication
   * Origin (object)
         number (int)  - element to compare for duplication    
         string1    
         string2      
   * Destination  (object)    
         number (int)  - element to compare for duplication    
         string1    
         string2      
    * Stop    (object)
         number (int)  - element to compare for duplication    
         string1    
         string2  
...other elements
这是伪代码。。。 我想这样做,但看起来我不能像这样使用flatMap,以及如何访问展平对象的不同元素以及嵌套对象上方一层的元素

List<Segment> Segments = purchasedCostTripSegments.stream()
   .flatMap(origin -> Stream.of(origin.getOrigin()))
   .flatMap(destination -> Stream.of(origin.getDestination()))
   .flatMap(stop -> Stream.of(origin.getStop()))
   .distinctbyKey(billing, originNumber, destinationNumber, stopNumber).collect(Collectors.toList());

也许这不是最好的方法…

考虑到您已经知道了解决方案和补救方法,您还可以扩展该解决方案,以通过多个属性查找distinct by。您可以使用列表来比较以下元素:

List<Segment> Segments = purchasedCostTripSegments.stream()
        .filter(distinctByKey(s -> Arrays.asList(s.getBilling(),s.getOrigin().getNumber(),
               s.getDestination().getNumber(),s.getStop().getNumber())))
        .collect(Collectors.toList());

如果在Segment类中重写equals&hashcode方法,那么使用此代码删除重复项就变得非常简单

Set<Segment> uniqueSegment = new HashSet<>();
List<Segment> distinctSegmentList = purchasedCostTripSegments.stream()
                    .filter(e -> uniqueSegment .add(e))
                    .collect(Collectors.toList());
System.out.println("After removing duplicate Segment  : "+uniqueSegment );
    

如何访问元素?我尝试只使用distinctbyKey,但无法访问嵌套对象。如果以这种方式实现equals,则不需要额外的集合,可以调用distinct而不是filter操作。