首页 > 解决方案 > 列表上的流过滤器保留一些过滤后的值

问题描述

所以我需要过滤一个项目列表,其中

物品定义:

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

我想简化这一点,而不必将逻辑分成两个不同的过滤器。

标签: javafilterstreamjava-stream

解决方案


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

推荐阅读