我有一个包含多个嵌套对象的复杂对象列表。我需要比较复杂对象中的 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());
也许这不是最好的方法......
最佳答案
考虑到您已经知道 Java 8 Distinct by property以及补救措施,您也可以扩展解决方案以通过多个属性查找不同的内容。您可以使用 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());
关于java - 如何使用 Java 流比较多个嵌套对象中的值来删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62575869/