首页 > 解决方案 > 将传统的 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

标签: javajava-streamexecution-timeparallelstream

解决方案


不要修改流中的集合,使用方法collect()

1.

List<??> addToBatchIdList = products.parallelStream()
        .filter(Objects::nonNull)
        .map(product::getCommodityId)
        .filter(Objects::nonNull)
        .collect(Collectors.toList());
batchIdList.addAll(addToBatchIdList);

推荐阅读