Home > Blockchain >  Convert java for loop into java 8 streams
Convert java for loop into java 8 streams

Time:09-28

Here is the old code which uses nested for loop to get the value of price and add this value into the PriceResponse object's data list.

  PriceResponse priceResponse = PriceResponse.builder()
          .data(new ArrayList<>())
          .build();

  for (Row row : rows) {
      String price = "0";
      for (Param param : row.getCell()) {
          if (param.getId().equals("1")) {
              price = param.getValue();
          }
      }

      priceResponses.getData().add(DataResponse.builder()
              .result(Result.builder().values(price).build())
              .build());
  }

How to rewrite this code using java streams?

CodePudding user response:

List<DataResponse> data = rows.stream()
        .map(row -> row.getCell().stream()
                .filter(param -> "1".equals(param.getId()))
                .map(Param::getValue)
                .findAny()
                .orElse("0"))
        .map(price -> DataResponse.builder()
                .result(Result.builder().values(price).build())
                .build())
        .toList(); // or Collectors.toList()

PriceResponse priceResponse = PriceResponse.builder()
          .data(data)
          .build();

CodePudding user response:

Maybe .streams() is not needed and rows has a method forEach. Maybe row does not have a Collection of cells

rows.forEach(row -> {
        String price = row.getCells().stream()
            .filter(param -> param.getId().equals("1"))
            .map(Param::getValue)
            .findAny().orElse("0");
        priceResponses.getData().add(DataResponse.builder()
          .result(Result.builder().values(price).build())
          .build());
    });

The problem here is that using builders the code already becomes very convoluted. I would keep having a variable price. Here I assume that any cell with an ID "1" suffices; not the last one.

  • Related