[英]adding lists into a set java
如何将事物列表添加到集合中?
当我执行 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<List<Food>> set = new HashSet<>();
这个set
对象是一个List
的Set
。 这意味着set
中的每个项目都是一个List<Food>
。
如何将事物列表添加到集合中?
当你想创建一个包含多个列表的 Set 时,你可以简单地使用set.add()
。 这会将sortedList
作为集合中的一个项目插入,这将最终成为您要查找的内容。
set.add(sortedList);
将所有指定的元素添加到指定的集合。 要添加的元素可以单独指定或作为数组指定。
由于您已经在使用 java 流,因此我将删除如下所示的aList
变量。
List<Food> sortedList = foods.stream().sorted(Comparator.comparing(a -> a.meal)).collect(Collectors.toList());
您实际上可以删除流操作。 首先将集合项收集到 List 对象,然后使用比较器中的方法引用执行排序。
List foodList = new ArrayList(set);
foodList.sort(Comparator.comparing(Food::meal));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.