java - 列表上的流过滤器保留一些过滤后的值
问题描述
所以我需要过滤一个项目列表,其中
物品定义:
{
id, category, title
}
类别可以是字符串类型的 T(标题)或 K(关键字)。问题是有时我们有可能有标题重复的类别 K 的项目。
因此,如果有标题重复,我需要过滤所有属于 K 类的项目以仅保留其中一个。
public List<Item> findSuggestions(String req) {
List<Item> items = service.findSuggestions(req);
Predicate<Item> isTitle = item -> item.getCategory().equals("T");
Predicate<Item> differentTitle = Utils.distinctByKey(Item::getTitle);
Predicate<Item> isKeyword = item -> item.getCategory().equals("K");
List<Item> result = items.stream()
.filter(isTitle)
.filter(differentTitle).collect(Collectors.toList());
result.addAll(items.stream().filter(isKeyword).collect(Collectors.toList()));
return result;
}
我想简化这一点,而不必将逻辑分成两个不同的过滤器。
解决方案
感谢@Amongalen,使用谓词的 OR AND 操作
public List<Item> findSuggestions(String req) {
List<Item> items = service.findSuggestions(req);
Predicate<Item> isTitle = item -> item.getCategory().equals("T");
Predicate<Item> differentTitle = Utils.distinctByKey(Item::getValue);
Predicate<Item> isKeyword = item -> item.getCategory().equals("K");
return items.stream().filter(isTitle.and(differentTitle).
or(isKeyword)).collect(Collectors.toList());
}
推荐阅读
- arrays - 如何解决这个分段错误?
- reactjs - 交换机内部的自定义路由/重定向未按预期工作
- laravel - Laravel:vue.js 路由 404 问题
- android - 使用 AGP 4.2.0 为每个子项目指定 android.useAndroidX
- amazon-connect - 如何识别客户是否断开连接与代理在亚马逊连接中挂断?
- post - RxJS - POST 多部分文件
- javascript - 在 ReactJs 中单击导航项时关闭可折叠的 Bootstrap 导航栏不起作用
- spring-boot - 在 Spring Boot 中使用删除查询计划
- kubernetes - 重启 kubernetes Pod 后 Cloudbees Jobs 受到打击
- reactjs - 将 Material-UI 组件与 React-Spring 动画库集成