java - 重做 foreach 到 .stream().map
问题描述
目前我有两个列表List<MonthlyFeePayment> monthlyFeePaymentList
和一个新列表List<FeePaymentStatusRequest> request = new ArrayList<>();
。我需要的是遍历所有monthlyFeePaymentList
元素并填写我的request
列表。FeePaymentStatus
由monthlyFeePaymentId
和组成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
在这种特定情况下是如何工作的吗?
解决方案
根据您在循环代码中已经定义的方式,的map
操作Stream
会将对象从 转换为 。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>
推荐阅读
- flask - 在 Eve check_auth 方法中访问 Flask 请求对象
- loops - 自动将递归转换为迭代
- c++ - basic_string 到 basic_string_view 隐式转换...呃,为什么?
- javascript - 将节点 api 部署到 heroku 时遇到问题
- java - 如何获取 GPS 时间或网络时间,location.getTime() 返回错误的设备日期和时间
- c# - 如何在 UWP/C# 中使用 svg 文件资源设置 AppBarButton 图标
- sql - Postgres 不同的查询计划 Prod/QA
- python - 为什么底部打印乱序?
- scala - 抽象类 Scala。教程和匿名课程中的错误
- django - 自定义社交表单