英文:
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循环,所以需要使用流操作。我的解决方案只添加了原型的列表,我在努力寻找如何修改它,以便添加具体的原型对象本身。
英文:
Here is my code:
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 ;
}
What I want to do in this method is I want to get a list of all different car prototypes given in car shop catalog. I should not use for loop, so stream comes into play. My solution is adds only lists of prototypes, and I struggle finding how to change it so it add specific prototypes themselves.
答案1
得分: 3
如果您有一个 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;
}
英文:
If you have a Stream<List<Foo>>
and want to convert it to List<Foo>
you can use flatMap
:
Stream<List<Foo>> stream = ...;
Stream<Foo> flatStream = stream.flatMap(List::stream);
List<Foo> list = flatStream.collect(Collectors.toList());
For your specific example:
public List<CarPrototype> allPrototypes() {
List<CarPrototype> prototypes = catalog.values().stream()
.flatMap(List::stream)
.collect(Collectors.toList());
return prototypes;
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论