简体   繁体   中英

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

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. This means every item in the set is a 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() . This will insert the sortedList as an item in the set which will end up what you are looking for.

set.add(sortedList);

When to use 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...)

Possible enhancements

  1. As you are already using java stream, I will get rid of aList variable like below.

     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 foodList = new ArrayList(set);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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