【问题标题】:Get rid of duplicates in one line instead of two with java 8 stream使用 java 8 流在一行而不是两行中删除重复项
【发布时间】:2019-11-18 08:26:03
【问题描述】:

可以用一行代码而不是单独的两行代码编写吗?因为我尝试在第一行添加.distinct(),但不知何故它不起作用。我没有在这里得到区别。

List<BgwContract> contractListWithDuplicates = monthlyFeePaymentList
           .stream()
           .map(MonthlyFeePayment::getBgwContract)
           .collect(Collectors.toList());

List<BgwContract> contractListWithoutDuplicates = contractListWithDuplicates
           .stream()
           .distinct()
           .collect(Collectors.toList());

【问题讨论】:

  • 哦好吧,我把它放在.map()之前。你能解释为什么它不起作用吗?因为据我了解,我想区分流,哪个是列表而不是地图。
  • 我加了解释

标签: java list duplicates java-stream


【解决方案1】:

您可以将distinct 与现有的Stream 本身一起使用:

List<BgwContract> contractListWithDuplicates = monthlyFeePaymentList
       .stream()
       .map(MonthlyFeePayment::getBgwContract) // Stream<BgwContract>
       .distinct() // here
       .collect(Collectors.toList());

【讨论】:

    【解决方案2】:

    既然你想解释distinct的正确位置:

    当你写作时:

    List<BgwContract> contractListWithDuplicates = monthlyFeePaymentList
               .stream()
               .distinct()
               .map(MonthlyFeePayment::getBgwContract)
               .collect(Collectors.toList());
    

    你得到一个 Stream 的不同 MonthlyFeePayment 实例(基于 MonthlyFeePayment 类的 equals 实现),然后将它们映射到 BgwContract 实例。两个不同的MonthlyFeePayment 实例可能映射到同一个BgwContract 实例,因此输出List 可能有重复。

    当你写作时:

    List<BgwContract> contractListWithDuplicates = monthlyFeePaymentList
               .stream()
               .map(MonthlyFeePayment::getBgwContract)
               .distinct()
               .collect(Collectors.toList());
    

    您首先将MonthlyFeePayment 实例映射到BgwContract 实例,然后才使用distinct() 删除重复项,这就是您想要的。

    【讨论】:

      【解决方案3】:

      使用 dintinct() 可以使用 equals() 方法比较元素。 您必须为您的 BgwContract 对象覆盖 equals()。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-14
        • 1970-01-01
        • 1970-01-01
        • 2020-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        相关资源
        最近更新 更多