Convert traditional for loop into Java Stream

139 views Asked by At

I'm trying to convert traditional for loop into Java Stream, but some problems are occurring. Basically, my Method execution taking too much time.When I describe reducing the method execution time. When converting the traditional for loop into JavaStream then the List size is 0, otherwise using the traditional for loop list size is not 0 and taking too much time. Please, Anyone, resolve this problem.

1.

 for (ProductProjection p : products) {
     if (p != null && p.getCommodityId() != 0) {
           batchIdList.add(p.getCommodityId());
     }
 }

The above code segment converts into the Java stream is correct or not, please edit me.

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);
         }
    }
}

The above code segment converts into the Java stream is correct or not, please edit me.

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);
          });
        });

second loop. List of ProductProjection size: 1238 and List of CourseBatch size: 1124

1

There are 1 answers

0
Ilya On

Do not modify the collection in the stream, use method collect()

1.

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