我有一个流操作,但它并没有完全按照我想要的方式进行
鉴于此数据结构
CatOwner {
id,
name,
List <CatType>
}
这段代码
List<CatOwner> catOwner = owners.stream()
.map(CatOwnerAccount:getCatOwnerAccountDetails)
.filter(Objects::nonNull)
.flatMap(catOwnerFunction)
.distinct()
.collect(Collectors.toList());
哪里
Function<CatOwnerAccountDetails, Stream<CatOwner>> catOwnerFunction = catOwnerDetails -> getCatOwners(catOwnerDetails);
我希望这能为我提供一个独特所有者的合并列表,将来自不同来源的所有猫组合在一起,因此与其生成此列表(因为它是平面映射,然后对具有不同列表的对象进行不同的操作),不如将其合并列表
所以不要生成这个
{ id : 1, name: Steve, cattype : [tabby, ginger] }
{ id : 1, name: Steve, cattype : [black] }
{ id : 2, name: Mandy, cattype : [tortashelle] }
{ id : 2, name: Mandy, cattype : [manx, grey] }
它会产生这个
{ id : 1, name: Steve, cattype : [tabby, ginger, black] }
{ id : 2, name: Mandy, cattype : [tortashelle, manx, grey] }
有人可以帮忙吗?
最佳答案
您可以通过创建中间 map 来做到这一点,但它不是很漂亮。
Collection<CatOwner> values = owners.stream()
// blah blah, the other stuff you had
.collect(
Collectors.toMap(
owner -> new Pair<>(owner.getId(), owner.getName()),
Function.identity(),
(a, b) -> {
a.getTypes().addAll(b.getTypes());
return a;
}
)
)
.values();
我用了javafx.util.Pair
作为关键,尽管任何将相等性实现为两个元素的组合相等性的元组类都可以。
owner -> new Pair<>(owner.getId(), owner.getName())
这表示 map 的值为 CatOwner
项目本身(即,映射是 Pair<Id, Name>
到 CatOwner
)。
Function.identity()
这表示如果发生冲突(两个具有相同 ID 和名称的项目),解决该问题的方法是添加 CatOwner
中的所有类型。到另一个。
(a, b) -> {
a.getTypes().addAll(b.getTypes());
return a;
}
结果是 Collection
,因为您获取了 map 的所有值。如果您确实想要/需要一个列表,您可以将值添加到新列表中。
new ArrayList<>(values);
关于java - 在 java 8 中对不同对象流执行平面映射时是否可以合并列表属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60435254/