繁体   English   中英

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

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

让我们假设我有一个对象:

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

我想要做的是访问MyObject列表的otherObjects属性,并将它们全部添加到otherObjects list

我可以将.forEach.addAll用于otherObjects list但我正在尝试查看是否可以使用lambdas来实现此目的。 我想到了类似的东西,但它似乎不起作用:

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

但似乎与对象类型存在冲突。 我猜这是因为我从一个对象流开始,最后得到一个列表流,它会混淆。 我怎样才能做到这一点? 更一般地说,如何将许多父对象的对象列表收集到一个列表中?

使用flatMap修复签名不匹配。 也喜欢方法参考和Haskell程序员赢得积分:)

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

你可以试试flatMap:

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

使用flatMap方法而不是最后一次map调用。 flatmap方法将给定函数返回的流连接成一个流。 像这样:

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