将传统的for循环转换为Java Stream

问题描述

我正在尝试将传统的for循环转换为Java Stream,但是出现了一些问题。基本上,我的方法执行花费太多时间。当我描述减少方法执行时间时。将传统的for循环转换为JavaStream时,列表大小为0,否则使用传统的for循环列表大小不为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);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...