0

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);
1
  • 3
    The types here are a little confusing.. are you after Set<List<Food>> or Set<Food>. If the former, then you want set.add(list), if the later then set.addAll(list) (and correct the type of the set). Commented Nov 8, 2020 at 11:28

1 Answer 1

4
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));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.