Java映射带有对象列表的列表

huangapple go评论76阅读模式
英文:

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&lt;Brand, List&lt;CarPrototype&gt;&gt; catalog;

    public List&lt;CarPrototype&gt; allPrototypes() {
        List&lt;CarPrototype&gt; 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&lt;List&lt;Foo&gt;&gt; and want to convert it to List&lt;Foo&gt; you can use flatMap:

Stream&lt;List&lt;Foo&gt;&gt; stream = ...;
Stream&lt;Foo&gt; flatStream = stream.flatMap(List::stream);
List&lt;Foo&gt; list = flatStream.collect(Collectors.toList());

For your specific example:

public List&lt;CarPrototype&gt; allPrototypes() {
    List&lt;CarPrototype&gt; prototypes = catalog.values().stream()
        .flatMap(List::stream)
        .collect(Collectors.toList());
    return prototypes;
} 

</details>



huangapple
  • 本文由 发表于 2020年4月7日 01:04:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/61065059.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定