简体   繁体   中英

Java 8 use filter if boolean true

I have list of objects, and other object which i want to find.

Lets call it List of ProductDto and Product

I want to filter of ProductDtos by names , and by type . And if field code is present - filter also by it.

In simple java code it will looks like:

ProductDto  find(List<ProductDto> productDtos, Product product) {
   for(ProductDto dto : productDtos) {
      if(dto.getName.equals(product.getName) && dto.getType.equals(product.getType)) {
         boolean isCodePresent = dto.getCode() != null && product.getCode() != null;
         if(!isCodePresent) return dto;
         else if(isCodePresent && dto .getCode.equals(product.getCode)) return dto;
      }
   }
   return null;
}

How will it looks in parralel stream?

productDtos.parralelStream()
    .filter(i -> i.getName().equals(product.getName) && // check if type is equal)
    // use filter if isCodePresent 
    .map(...)
    .collect(Collectors.toList());

The many null tests muddle the clearity.

ProductDto find(List<ProductDto> productDtos, Product product) {
   return ProductDts.parallelStream()
      .filter(dto -> dto.getName.equals(product.getName)
          && dto.getType.equals(product.getType)
          && ((dto.getCode() == null || product.getCode() == null)
              || 
              (dto.getCode() != null && product.getCode() != null
                  && dto.getCode.equals(product.getCode))
              ))
      .findAny().orElse(null);
}

Safer and shorter without orElse would be:

Optional<ProductDto> find(List<ProductDto> productDtos, Product product) {
   return ProductDts.parallelStream()
      .filter(dto -> dto.getName.equals(product.getName)
          && dto.getType.equals(product.getType)
          && (dto.getCode() == null) == (product.getCode() == null)
          && (product.getCode() == null || dto.getCode.equals(product.getCode)))
    .findAny();
}

Also the filter condition a bit simplified.

Eliminating invariant subexpression:

Optional<ProductDto> find(List<ProductDto> productDtos, Product product) {
   boolean productCodeNull = product.getCode() == null;
   return ProductDts.parallelStream()
      .filter(dto -> dto.getName.equals(product.getName)
          && dto.getType.equals(product.getType)
          && (dto.getCode() == null) == productCodeNull 
          && (productCodeNull || dto.getCode.equals(product.getCode)))
    .findAny();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM