首页 > 解决方案 > 重做 foreach 到 .stream().map

问题描述

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

我目前的实现:

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在这种特定情况下是如何工作的吗?

标签: javafor-loopcollectionsjava-8java-stream

解决方案


根据您在循环代码中已经定义的方式,的map操作Stream会将对象从 转换为 。MonthlyFeePaymentFeePaymentStatusRequestfor

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

推荐阅读