java - 使用 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());
解决方案
您可以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(...)
推荐阅读
- python - 在 Python 中以字典形式返回结果的函数
- excel - Telerik RadGridView.ExportToXlsx - 将单元格格式化为数字
- sql-server - 在 where 子句中使用自联接和 group bys 优化查询
- javascript - 如何为对象数组提供 ng-options?
- android - 从头开始创建像 SnapChat 或 Instagram 这样的相机 (Android)
- jpa - 带有 CriteriaQuery 和 ORDER BY 乘法的 JPA
- multithreading - Delphi crSQLWait 鼠标光标问题
- android - 将 Lottie 库添加到 Android Studio 项目中给了我这个:“无法解决依赖关系”
- c++ - 如何在 map [] 运算符中重载元组?
- c# - 如何在具有多个项目的 .NET Core 中创建 docker 映像?