【问题标题】:Java 8: Filter list inside object with another listJava 8:使用另一个列表过滤对象内的列表
【发布时间】:2019-12-25 03:43:39
【问题描述】:

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

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

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

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

带循环的示例代码:

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

谢谢!

【问题讨论】:

  • 流不是为修改集合而设计的。您在寻找什么最终结果?
  • 类别类会是什么样子?在我看来,最好使用enum 并使用EnumSet 而不是List<Category>
  • 食品对象列表,仅包含类别不在excludedCategories 列表中的食品对象

标签: java list loops java-stream


【解决方案1】:

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

【讨论】:

  • 您的第一种方法将仅包含 categories 作为我相信的列表。不是过滤后的Food 列表
  • @SunilDabburi 你是对的!它将返回 List<Category> ,而不是 List<Food>
【解决方案2】:

使用streamfilter excluded 类别如下

foodList.stream()
        .filter(f -> f.categories.stream().noneMatch(c -> excludedCategories.contains(c)))
        .collect(Collectors.toList());

【讨论】:

    【解决方案3】:

    你可以这样做

        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);
    

    【讨论】:

    • 什么是getCats
    • getCategories 是获取类别列表的 getter 方法。
    【解决方案4】:
    foodList.removeIf(f -> f.getCategories().stream().anyMatch(excludeCategories::contains));
    

    你可以使用 removeIf 和 anyMatch 来达到想要的结果

    【讨论】:

      猜你喜欢
      • 2018-09-03
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      • 2019-01-31
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多