我有一个名为"foodList“的列表,其中包含"Food”类型的元素。对象Food包含一个名为“类别”的“类别”类型的列表。
我目前正在实施一种搜索算法,通过排除某些类别来过滤食物。
排除的类别存储在名为"excludedCategories“的列表中。
我如何使用Java8和streams,通过排除其foodList包含excludedCategories列表中的任何元素的foodList来过滤excludedCategories?
带循环的示例代码:
for (Food f: foodList)
{
for (Category c: f.categories)
{
if (excludedCategories.contains(c))
{
// REMOVE ITEM FROM foodList
}
}
}
谢谢!
发布于 2019-12-25 03:53:20
不应该使用流来修改List
。相反,您应该返回一个只包含适当元素的新List
。您可以简单地翻转一下逻辑并使用过滤器:
foodList.stream().flatMap(e -> e.categories.stream())
.filter(c -> !excludedCategories.contains(c))
.collect(Collectors.toList());
但是,使用内置的方法要简单得多:
foodList.removeIf(e -> !Collections.disjoint(e.categories, excludedCategories));
发布于 2019-12-25 04:10:47
使用stream
对excluded
类别进行filter
,如下所示
foodList.stream()
.filter(f -> f.categories.stream().noneMatch(c -> excludedCategories.contains(c)))
.collect(Collectors.toList());
发布于 2019-12-25 04:42:06
你可以这样做
foodList.stream().filter(f -> {
f.setCats(f.getCats().stream().filter(c -> (!excludedCategories.contains(c))).collect(Collectors.toList()));
return true;
}).collect(Collectors.toList()).forEach(System.out::println);
https://stackoverflow.com/questions/59475050
复制相似问题