简体   繁体   English

使用lambdas获取对象列表的hashmap值

[英]Getting the hashmap values of an object list using lambdas

Lets assume I have an object: 让我们假设我有一个对象:

class MyObject {
    private int id;
    private HashMap<Integer, OtherObject> otherObjects;
}

What I want to do is access the otherObjects property of a list of MyObject and add them all to a otherObjects list . 我想要做的是访问MyObject列表的otherObjects属性,并将它们全部添加到otherObjects list

I could use a .forEach and .addAll into the otherObjects list but I'm trying see if it is possible to use lambdas to achieve this. 我可以将.forEach.addAll用于otherObjects list但我正在尝试查看是否可以使用lambdas来实现此目的。 I thought of something like this but it doesn't seem to work: 我想到了类似的东西,但它似乎不起作用:

myObjectList.stream()
    .map(o -> o.getOtherObjects())
    .map(oo -> oo.values())
    .collect(Collectors.toList());

But there seems to be a conflict with the object types. 但似乎与对象类型存在冲突。 I'm guessing it is because I start with a stream of objects and end up with a stream of lists and it gets confused. 我猜这是因为我从一个对象流开始,最后得到一个列表流,它会混淆。 How can I achieve this? 我怎样才能做到这一点? And more generally, how can I gather a list of objects of many parent objects into a single list? 更一般地说,如何将许多父对象的对象列表收集到一个列表中?

Use flatMap to fix the signature mismatch. 使用flatMap修复签名不匹配。 Also prefer method references and win points with Haskell programmers :) 也喜欢方法参考和Haskell程序员赢得积分:)

myObjectList.stream()
            .map(MyObject::getOtherObjects)
            .map(Map::values)
            .flatMap(Collection::stream)
            .collect(Collectors.toList());

You can try flatMap: 你可以试试flatMap:

myObjectList.stream()
            .flatMap(o -> o.getOtherObjects().values().stream())
            .collect(Collectors.toList());

Use the flatMap method instead of the last map call. 使用flatMap方法而不是最后一次map调用。 The flatmap method concatenates the streams that the given function returns, into one stream. flatmap方法将给定函数返回的流连接成一个流。 Like this: 像这样:

myObjectList.stream()
    .map(o -> o.getOtherObjects())
    .flatMap(oo -> oo.values().stream())
    .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM