So I need to filter a list of items where
Item definition:
{
id, category, title
}
Category can be T (title) or K(keyword) of type string. The problem is that sometimes we have items of category K that can have title repetition.
So I need to filter all of the items that are of category K to keep only one of them if there is title repetition.
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;
}
I would like to simplify this, without having to separate the logic into two different filters.
Thanks to @Amongalen, use OR AND operations of Predicates
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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.