Search code examples
javasortingcollect

How to collect a list within a list


I have class Stores which contains array of Items.

public class Store extends NamedEntity{

    String webAddress;
    Item[] items;

    public Store(String name, String webAddress, Set<Item> items) {
        super(name);
        this.webAddress = webAddress;
        this.items = items.toArray(new Item[0]);

    }

Each item (class Item) has different volumes and I am adding items to the store. Let's say I have 20 items and I add 10 to 2 or 3 different stores and I have to sort these items in stores based on their volume.

I'd sort them this way:

List<Item> storedItemsSorted = storedItems.stream()
                .sorted(Comparator.comparing(Item::getVolume))
                .collect(Collectors.toList());

I don't know how to put items into this list storedItemsSorted.

I tried with something like this but it doesn't work:

List <Item> storedItems = storeList
                .stream()
                .map(s->s.getItems())
                .collect(Collectors.toList());

It says:

Required type: List <Item>

Provided:List <Item[]>

Solution

  • Perhaps you are looking for flatMap instead of map. flatMap works on a stream of lists, and maps to stream of items.

    List <Item> storedItems = storeList
                    .stream()
                    .flatMap(s->Arrays.stream(s.getItems()))
                    .collect(Collectors.toList());