列表中的流过滤器保留一些过滤值

时间:2020-11-09 10:45:38

标签: java filter stream java-stream

所以我需要过滤其中的项目列表

项目定义:

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

我想简化此过程,而不必将逻辑分为两个不同的过滤器。

1 个答案:

答案 0 :(得分:0)

感谢@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());
        }
相关问题