【问题标题】:adding lists into a set java将列表添加到一组java中
【发布时间】:2020-11-08 11:24:44
【问题描述】:

如何将事物列表添加到集合中?

当我执行 set.addAll 时出现错误

必填类型:集合

提供类型:列表

public static Set<List<Food>> getAllMealPlans(Set<Food> foods, int numMeals) {
        Set<List<Food>> set = new HashSet<>();
        List<Food> aList = new ArrayList<Food>(foods);
        List<Food> sortedList = aList.stream().sorted(Comparator.comparing(a -> a.meal)).collect(Collectors.toList());
        set.addAll(sortedList);

【问题讨论】:

  • 这里的类型有点混乱.. 你是在 Set> 还是 Set 之后。如果是前者,那么你想要 set.add(list),如果是后者,那么 set.addAll(list) (并更正集合的类型)。

标签: java list set


【解决方案1】:
Set<List<Food>> set = new HashSet<>();

这个set 对象是SetList s。这意味着set 中的每个项目都是List&lt;Food&gt;

如何将事物列表添加到集合中?

当你想创建一个包含多个列表的集合时,你可以简单地使用set.add()。这将插入 sortedList 作为集合中的一个项目,这将最终成为您要查找的内容。

set.add(sortedList);

什么时候使用 addAll()?

将所有指定元素添加到指定集合。 要添加的元素可以单独指定,也可以作为数组指定。

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#addAll(java.util.Collection,%20T...)

可能的改进

  1. 由于您已经在使用 java 流,我将删除 aList 变量,如下所示。

        List<Food> sortedList = foods.stream().sorted(Comparator.comparing(a -> a.meal)).collect(Collectors.toList());
    
  2. 您实际上可以删除流操作。首先将集合项收集到 List 对象,然后使用比较器中的方法引用执行排序。

    列出 foodList = new ArrayList(set);

    foodList.sort(Comparator.comparing(Food::meal));

【讨论】:

    猜你喜欢
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多