Java 8 如果布尔值为真则使用过滤器

Java 8 use filter if boolean true

我有对象列表,以及我想查找的其他对象。

我们称它为 ProductDtoProduct

的列表

我想按 namestype 筛选 ProductDtos。如果字段 code 存在 - 也按它过滤。

在简单的 java 代码中,它看起来像:

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

它在并行流中看起来如何?

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

大量无效测试混淆了清晰度。

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

没有 orElse 会更安全更短:

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

过滤条件也稍微简化了。

消除不变子表达式:

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