可以用一行代码而不是分开的两行代码来写吗?因为我尝试在第一行添加 .distinct()
但不知何故它不起作用。我在这里没有区别。
List<BgwContract> contractListWithDuplicates = monthlyFeePaymentList
.stream()
.map(MonthlyFeePayment::getBgwContract)
.collect(Collectors.toList());
List<BgwContract> contractListWithoutDuplicates = contractListWithDuplicates
.stream()
.distinct()
.collect(Collectors.toList());
最佳答案
您可以将 distinct
与您现有的 Stream
本身一起使用:
List<BgwContract> contractListWithDuplicates = monthlyFeePaymentList
.stream()
.map(MonthlyFeePayment::getBgwContract) // Stream<BgwContract>
.distinct() // here
.collect(Collectors.toList());
关于java - 使用 Java 8 流在一行而不是两行中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58910485/