Java 8:用另一个列表过滤对象内部的列表

时间:2019-12-25 03:43:39

标签: java list loops java-stream

我有一个名为“ foodList”的列表,其中包含“ Food”类型的元素。食物对象包含一个名为“类别”的“类别”列表。

我目前正在实施一种搜索算法,通过排除某些类别来过滤食物。

排除类别存储在名为“ excludedCategories”的列表中。

我如何使用Java 8和流,通过排除其categoryList包含exclude includedCategories列表中任何元素的Food对象来过滤foodList?

带有循环的示例代码:

for (Food f: foodList)
{
     for (Category c: f.categories)
     {
          if (excludedCategories.contains(c))
          {
               // REMOVE ITEM FROM foodList
          }
     }
}

谢谢!

4 个答案:

答案 0 :(得分:2)

不应使用流来修改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));

Collections::disjoint

Collections::removeIf

答案 1 :(得分:1)

使用streamfilter的{​​{1}}类别

excluded

答案 2 :(得分:0)

你可以这样做

<sqlite3.Cursor object at 0x126cff9d0>

答案 3 :(得分:0)

foodList.removeIf(f -> f.getCategories().stream().anyMatch(excludeCategories::contains));

您可以使用removeIf和anyMatch获得所需的结果