我有一个包含多个嵌套对象的复杂对象列表。我需要比较复杂对象中的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());也许这不是最好的方法。
发布于 2020-06-25 21:32:53
考虑到您已经了解了Java 8 Distinct by property和补救措施,您可以扩展该解决方案以查找多个属性的distinct。您可以使用List来比较以下元素:
List<Segment> Segments = purchasedCostTripSegments.stream()
.filter(distinctByKey(s -> Arrays.asList(s.getBilling(),s.getOrigin().getNumber(),
s.getDestination().getNumber(),s.getStop().getNumber())))
.collect(Collectors.toList());发布于 2020-06-25 21:58:38
如果覆盖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 );https://stackoverflow.com/questions/62575869
复制相似问题