假设我有一个对象:
class MyObject {
private int id;
private HashMap<Integer, OtherObject> otherObjects;
}
我想要做的是访问 MyObject
列表的 otherObjects
属性,并将它们全部添加到 otherObjects
列表中
.
我可以在 otherObjects
list
中使用 .forEach
和 .addAll
但我正在尝试查看是否可以使用 lambda 来实现这一点。我想到了这样的事情,但似乎不起作用:
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());
关于java - 使用 lambda 获取对象列表的 hashmap 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32375771/