Java 8 Stream“收集和分组"映射到多个键的对象 [英] Java 8 Stream "collect and group by" objects that map to multiple keys
问题描述
我有以下物品:
public class Item {
String value;
List<Person> owners;
Person creator;
}
public class Person {
String name;
int id;
Person manager;
}
现在我有一个包含 3 个 Item 对象的列表:
now i have the a list containing 3 Item objects:
i1 -> {value="1", owners=[p1, p2, p3], creator=p4}
i2 -> {value="2", owners=[p2, p3], creator=p5}
i3 -> {value="3", owners=[p5], creator=p1}
Person 对象如下:
the Person objects are as follows:
p1 -> {manager=m1, ...}
p2 -> {manager=m2, ...}
p3 -> {manager=m3, ...}
p4 -> {manager=m2, ...}
p5 -> {manager=m1, ...}
我想根据所有者和创建者的管理者对 Item 对象流进行分组.结果 Map<Person, List<Item>>
应如下所示:
I want to group the stream of Item objects based on managers of the owners and creator. The result Map<Person, List<Item>>
should look like:
{
m1: [i1, i2, i3],
m2: [i1, i2],
m3: [i1, i2]
}
我认为使用 Stream 和 Collector API,我可以制作从 Item 到管理器的映射,首先 Map
,然后反向映射.但是有什么方法可以只使用 Stream 和 Collectors 来制作我想要的映射吗?
I think using Stream and Collector APIs, I can make the map from Item to managers, Map<Item, List<Person>>
first, then reverse the mapping. But is there any way to make the mapping I want using Stream and Collectors only?
推荐答案
我认为,这只有通过中间对"值来记住人员/经理和原始项目之间的关联才有可能.在 Java 的标准 API 中没有标准对类型的情况下,我们不得不求助于最接近 Pair
类型的 Map.Entry
:
I think, this is only possible with an intermediate "pair" value to remember the association between a person/manager and the originating item. In absence of a standard pair type in Java’s standard API, we have to resort to Map.Entry
which comes closest to a Pair
type:
Map<Person, List<Item>> map = list.stream()
.flatMap(item->item.getOwners().stream()
.map(p->new AbstractMap.SimpleEntry<>(p.getManager(), item)))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
使用 import static
改进后,我们得到
after improving it using import static
we get
Map<Person, List<Item>> map = list.stream()
.flatMap(item->item.getOwners().stream().map(p->new SimpleEntry<>(p.getManager(), item)))
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
结果
m1: [i1,i3]
m3: [i1,i2]
m2: [i1,i2]
这是不同的,因为首先,标准地图没有定义的顺序,其次,我认为你对你的期望犯了一个错误,因为 m1
与 i2
在你的示例数据.
which differs because first, the standard map has no defined ordering, second, I think you made a mistake regarding you expectation as m1
is not associated with i2
in your example data.
这篇关于Java 8 Stream“收集和分组"映射到多个键的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!