首页 > 解决方案 > 使用 Java 8 流处理 null 或空集合

问题描述

我有公司的集合,每个公司都有根据复杂的多级条件过滤的部门和部门列表。当公司中没有找到部门时,我想从其他来源获取部门信息,然后继续过滤条件作为下一步。以下实现是实现的最佳方法吗?

   public class Company{
     private List<Department> departments;
   }

       companies.stream().forEach(c -> {
            if(CollectionUtils.isEmpty(c.getDepartments())){
                //handle no department 
                //Set the department after getting from different source
            }
        });
 
companies.stream()
    .filter(c -> CollectionUtils.isNotEmpty(c.getDepartments()))
    .filter(c -> c.getDepartments().stream()
            .anyMatch(d -> condition))
    .collect(Collectors.toList());

标签: javajava-stream

解决方案


您可以if/else按照已经建议的方式在代码中执行该语句。如果你想让你的同事看起来很奇怪(谁不喜欢这样?),你可以这样写:

companies.stream()
         .map(x -> Optional.ofNullable(x.getDepartments())
                           .flatMap(dep -> dep.size() == 0 ? Optional.empty() : Optional.of(dep))
                           .orElse(List.of()) // get it from another source...
        ).filter(...)

推荐阅读