[英]Java map with lists of objects to list
這是我的代碼:
public class CarShop {
private final HashMap<Brand, List<CarPrototype>> catalog;
public List<CarPrototype> allPrototypes() {
List<CarPrototype> prototypes = catalog.values().stream().collect(Collectors.toList())
return prototypes ;
}
我想在這種方法中做的是我想獲得汽車商店目錄中給出的所有不同汽車原型的列表。 我不應該使用 for 循環,所以 stream 發揮作用。 我的解決方案是只添加原型列表,我很難找到如何更改它,以便它自己添加特定的原型。
如果您有Stream<List<Foo>>
並想將其轉換為List<Foo>
您可以使用flatMap
:
Stream<List<Foo>> stream = ...;
Stream<Foo> flatStream = stream.flatMap(List::stream);
List<Foo> list = flatStream.collect(Collectors.toList());
對於您的具體示例:
public List<CarPrototype> allPrototypes() {
List<CarPrototype> prototypes = catalog.values().stream()
.flatMap(List::stream)
.collect(Collectors.toList());
return prototypes;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.