Java 8 Stream query - need to replace if inside for each with some streams method

515 views Asked by At
request
.getCustomer()
.stream()
.filter(custDetails -> custDetails.getCorrespondenceAddress() != null)
.forEach(
          custDetails -> {
            if (validateNotNull(
                custDetails.getCorrespondenceAddress().getHasCorrespondenceAddress())) {
              customAttributesList.add(
                  generateCustomAttributeHasCorrespondenceAddress(
                    custDetails.getCorrespondenceAddress().getHasCorrespondenceAddress(),
                      customerCountCorrespondenceAddress));
            }
            if (validateNotNull(
                custDetails
                    .getCorrespondenceAddress()
                    .getCorrespondenceAddressPostcode())) {
              customAttributesList.add(
                  generateCustomAttributeCorrespondenceAddressPostcode(
                      custDetails
                          .getCorrespondenceAddress()
                          .getCorrespondenceAddressPostcode(),
                      customerCountCorrespondenceAddressPostcode));
            }
            customerCountCorrespondenceAddress++;
            customerCountCorrespondenceAddressPostcode++;
          });

Here request contains a list of customers, list of customer is having correspondence address, correspondence addrress is having 2 fields. I am trying to map these fields to a custom attribute list. Is there any way to replace the if in for each block with some streams method?

1

There are 1 answers

0
Ankitha J On BEST ANSWER

Looking at your code, might need to call stream 2 times. One for address and other for postalCode.

  request
    .getCustomer()
    .stream()
    .filter(custDetails -> custDetails.getCorrespondenceAddress() != null)
    .filter(custDetails -> validateNotNull(             custDetails.getCorrespondenceAddress().getHasCorrespondenceAddress()))
    .forEach(custDetails -> {customAttributesList.add(
                      generateCustomAttributeHasCorrespondenceAddress(
                        custDetails.getCorrespondenceAddress().getHasCorrespondenceAddress(),
                          customerCountCorrespondenceAddress)))
                customerCountCorrespondenceAddress++;});


request
.getCustomer()
.stream()
.filter(custDetails -> custDetails.getCorrespondenceAddress() != null)
.filter(custDetails -> validateNotNull(
                custDetails.getCorrespondenceAddress().getHasCorrespondenceAddress()))
.forEach(
          custDetails -> {
              customAttributesList.add(
                  generateCustomAttributeCorrespondenceAddressPostcode(
                      custDetails
                          .getCorrespondenceAddress()
                          .getCorrespondenceAddressPostcode(),
                      customerCountCorrespondenceAddressPostcode));
            }
            customerCountCorrespondenceAddressPostcode++;
          });