简体   繁体   English

将列表添加到集合中 java

[英]adding lists into a set java

How do I add a list of things into a set?如何将事物列表添加到集合中?

When I do set.addAll I get an error当我执行 set.addAll 时出现错误

required type :Collection <?所需类型:集合 <? extends List>扩展列表>

provided type :List提供的类型:列表

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<List<Food>> set = new HashSet<>();

This set object is a Set of List s.这个set对象是一个ListSet This means every item in the set is a List<Food> .这意味着set中的每个项目都是一个List<Food>

How do I add a list of things into a set?如何将事物列表添加到集合中?

As you want to create a Set which contains multiple lists, you can simply use set.add() .当你想创建一个包含多个列表的 Set 时,你可以简单地使用set.add() This will insert the sortedList as an item in the set which will end up what you are looking for.这会将sortedList作为集合中的一个项目插入,这将最终成为您要查找的内容。

set.add(sortedList);

When to use addAll()?何时使用 addAll()?

Adds all of the specified elements to the specified collection.将所有指定的元素添加到指定的集合。 Elements to be added may be specified individually or as an array.要添加的元素可以单独指定或作为数组指定。

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

Possible enhancements可能的改进

  1. As you are already using java stream, I will get rid of aList variable like below.由于您已经在使用 java 流,因此我将删除如下所示的aList变量。

     List<Food> sortedList = foods.stream().sorted(Comparator.comparing(a -> a.meal)).collect(Collectors.toList());
  2. You can actually remove stream operations.您实际上可以删除流操作。 First collect set items to a List object and then perform sorting with a method references in your comparator.首先将集合项收集到 List 对象,然后使用比较器中的方法引用执行排序。

    List foodList = new ArrayList(set); List foodList = new ArrayList(set);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM