java - 将传统的 for 循环转换为 Java Stream
问题描述
我正在尝试将传统的 for 循环转换为 Java Stream,但出现了一些问题。基本上,我的方法执行花费了太多时间。当我描述减少方法执行时间时。将传统的for循环转换为JavaStream时List size为0,否则使用传统for循环的list size不是0,耗时太长。请,任何人,解决这个问题。
1.
for (ProductProjection p : products) {
if (p != null && p.getCommodityId() != 0) {
batchIdList.add(p.getCommodityId());
}
}
上述代码段转换成Java流是否正确,请编辑我。
products.parallelStream().filter(product -> Objects.nonNull(product) && (product.getCommodityId() != 0))
.forEach(pro -> {
batchIdList.add(pro.getCommodityId());
});
2.
for (ProductProjection p : products) {
for (CourseBatch cb : batches) {
if (cb.getId() == p.getCommodityId()) {
CourseProductResponse cpr = new CourseProductResponse();
if (cb.getCourse() != null) {
cpr.setCourseName(cb.getCourse().getCourseTitle());
cpr.setBatchName(cb.getBatchName());
}
cpr.setProduct(p);
response.add(cpr);
}
}
}
上述代码段转换成Java流是否正确,请编辑我。
products.parallelStream()
.forEach(product -> {
batches.parallelStream().peek(e -> System.out.println("Batches : " + e))
.filter(cb -> cb.getId() == product.getCommodityId())
.forEach(cb -> {
CourseProductResponse cpr = new CourseProductResponse();
if (Objects.nonNull(cb.getCourse())) {
cpr.setCourseName(cb.getCourse().getCourseTitle());
cpr.setBatchName(cb.getBatchName());
}
cpr.setProduct(product);
response.add(cpr);
});
});
第二个循环。ProductProjection 大小列表:1238 和 CourseBatch 大小列表:1124
解决方案
不要修改流中的集合,使用方法collect()
1.
List<??> addToBatchIdList = products.parallelStream()
.filter(Objects::nonNull)
.map(product::getCommodityId)
.filter(Objects::nonNull)
.collect(Collectors.toList());
batchIdList.addAll(addToBatchIdList);
推荐阅读
- swift - 如何使用 Alamofire 将 SwiftUI 图像上传到我的后端
- python - AWS Elastic Beanstalk 找不到 Django App 的静态文件
- .net - 在 Ubuntu 和 Certbot 上使用 SSL 的 Blazor
- javascript - 已解决:是否将 json 对象输入函数但无法获取其数据?
- powerbi - 特定分支机构加班的员工人数
- amazon-web-services - AWS - 日志聚合和可视化
- reactjs - 如何从 mapStateToProps() 中获取 props 并在 useEffect() 的依赖参数中使用它们
- java - 如何在 Java 中使用递归从 N 叉树中提取最大值
- python - 当在表中创建行时从 django 中的另一个表中获取值
- bitbucket-pipelines - 如何在我的 bitbucket-pipelines.yml 文件中使用 build.gradle 文件中的版本