[英]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.