我有类 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[]>
最佳答案
也许您正在寻找 flatMap
而不是 map
。 flatMap
适用于列表流,并映射到项目流。
List <Item> storedItems = storeList
.stream()
.flatMap(s->Arrays.stream(s.getItems()))
.collect(Collectors.toList());
关于java - 如何收集列表中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70052797/