【问题标题】:Redo foreach to .stream().map重做 foreach 到 .stream().map
【发布时间】:2020-01-20 03:29:08
【问题描述】:

目前我有两个列表 List<MonthlyFeePayment> monthlyFeePaymentList 和一个新列表 List<FeePaymentStatusRequest> request = new ArrayList<>();。我需要的是遍历所有monthlyFeePaymentList 元素并填写我的request 列表。 FeePaymentStatusmonthlyFeePaymentIdsourceSystem 组成(始终相同)。

我目前的实现:

List<FeePaymentStatusRequest> request = new ArrayList<>();
    for (MonthlyFeePayment monthlyFeePayment : monthlyFeePaymentList) {
        request.add(new FeePaymentStatusRequest(monthlyFeePayment.getMonthlyFeePaymentId().toString(), "BGW"));
    }

我想用.stream().map() 重新做,但我想不通。考虑到它只有两个列表,这应该很容易。但我不知道应该先列出哪个列表,request.stream() 还是 monthlyFeePaymentList.stream()?您能解释一下Stream#map 在这种特定情况下的工作原理吗?

【问题讨论】:

    标签: java for-loop collections java-8 java-stream


    【解决方案1】:

    你正在迭代的那个:

    List<FeePaymentStatusRequest> request = monthlyFeePaymentList.stream()
        .map(monthlyFeePayment -> new FeePaymentStatusRequest(monthlyFeePayment.getMonthlyFeePaymentId().toString(), "BGW"))
        .collect(Collectors.toList());
    

    您可以随后收集它而无需显式创建新列表。

    【讨论】:

      【解决方案2】:

      您无需显式创建输出List

      Stream 覆盖您的输入 Listmap 每个 MonthlyFeePaymentFeePaymentStatusRequest 实例,collectList

      List<FeePaymentStatusRequest> request = 
          monthlyFeePaymentList.stream()
                               .map(monthlyFeePayment -> new FeePaymentStatusRequest(monthlyFeePayment.getMonthlyFeePaymentId().toString(), "BGW"))
                               .collect(Collectors.toLis());
      

      【讨论】:

        【解决方案3】:

        Streammap 操作会将对象从MonthlyFeePayment 转换为FeePaymentStatusRequest 的操作,因为您已经在for 循环代码中定义了这种方式。

        List<FeePaymentStatusRequest> request = monthlyFeePaymentList
                  .stream() // Stream<MonthlyFeePayment>
                  .map(monthlyFeePayment -> new FeePaymentStatusRequest(
                           monthlyFeePayment.getMonthlyFeePaymentId().toString(), "BGW")) // Stream<FeePaymentStatusRequest>
                  .collect(Collectors.toList()); // List<FeePaymentStatusRequest>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-17
          • 2015-07-08
          • 2016-04-15
          • 1970-01-01
          • 1970-01-01
          • 2017-10-17
          • 2021-09-30
          • 1970-01-01
          相关资源
          最近更新 更多