2

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[]>
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
JurajC
  • 99
  • 2
  • 8
  • I don't understand what you mean by *I add 10 to 2 or 3 different stores*. What are the type of `storedItems` and `storeList` - I believe they are `List` and `List` respectively. Are you looking to combine the items from multiple stores? – Thiyagu Nov 21 '21 at 08:06
  • So I have list of stores which containts list of items and I am inputting items first so I create 20 objects of class Item and then select which of them to add into stores and I can for example add 5 items into store1 and 5 items into store 2. After I do that, I have to sort just items that are in stores based on their volume. But I am not sure how to add items from list of items from stores into a new list of items using lambdas. – JurajC Nov 21 '21 at 08:24

1 Answers1

4

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());
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78