【问题标题】:How to collect a list within a list如何在列表中收集列表
【发布时间】:2021-12-31 06:54:33
【问题描述】:

我有包含 Items 数组的类 Stores。

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

    }

每个项目(项目类)都有不同的数量,我正在向商店添加项目。假设我有 20 件商品,我添加了 10 到 2 或 3 个不同的商店,我必须根据它们的数量在商店中对这些商品进行分类。

我会这样排序:

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

我不知道如何将项目放入此列表 storedItemsSorted。

我试过这样的东西,但它不起作用:

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

上面写着:

Required type: List <Item>

Provided:List <Item[]>

【问题讨论】:

  • 我不明白你的意思是什么我添加了 10 到 2 或 3 个不同的商店storedItemsstoreList 的类型是什么 - 我相信它们分别是 List&lt;Item&gt;List&lt;Store&gt;。您是否希望合并来自多个商店的商品?
  • 所以我有包含项目列表的商店列表,我首先输入项目,所以我创建了 20 个 Item 类的对象,然后选择将其中哪些添加到商店中,例如我可以添加 5将物品放入商店 1,将 5 件物品放入商店 2。之后,我必须根据物品的数量对商店中的物品进行分类。但我不确定如何使用 lambdas 将商店中的商品列表中的商品添加到新的商品列表中。

标签: java sorting collect


【解决方案1】:

也许您正在寻找flatMap 而不是mapflatMap 作用于列表流,并映射到项目流。

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

【讨论】:

  • getItems 返回一个数组。它没有 stream() 方法。一种选择是使用Arrays.stream()
  • @user7 真实,已更新。
猜你喜欢
  • 2015-07-26
  • 2021-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-04
  • 1970-01-01
相关资源
最近更新 更多