Java 8 Stream 查询 - 需要用一些 streams 方法替换 if inside

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

提问人:Aman Gupta 提问时间:5/31/2022 更新时间:6/18/2022 访问量:455

问:

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

这里请求包含客户列表,客户列表有通讯地址,通讯地址有 2 个字段。我正在尝试将这些字段映射到自定义属性列表。有没有办法用一些流方法替换每个块的 if in?

if-语句 foreach java-8 轻量级流 API

评论

0赞 Vincent Passau 6/3/2022
为这些“if”块做一个谓词,并在你的 foreach 之前使用 .filter()

答:

0赞 Ankitha J 6/18/2022 #1

查看代码时,可能需要调用流 2 次。一个用于地址,另一个用于邮政编码。

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