[英]Grouping items in a reactive stream
Say that I have a finite stream of these objects假设我有这些对象的有限 stream
class Item {
private int id;
private List<Tag> tags;
}
Flux<Item> publisher;
Say that these are the items in the stream:假设这些是 stream 中的项目:
[
{"id": 1, "tags": [{"value":"A"}]},
{"id": 2, "tags": [{"value":"B"}]},
{"id": 2, "tags": [{"value":"C"}]},
]
I want to group them by id and join the corresponding values together.我想按 id 对它们进行分组并将相应的值连接在一起。
[
{"id": 1, "tag": [{"value":"A"}]},
{"id": 2, "tag": [{"value":"B"}, {"value":"C"}]},
]
How can I do this on the publisher我怎样才能在发布者上做到这一点
You can use collectMultimap
which allows you to have Map<K, Collection<T>>
:您可以使用
collectMultimap
,它允许您拥有Map<K, Collection<T>>
:
publisher.collectMultimap(Item::getId)
.subscribe(groupById -> System.out.println(groupById.toString()));
Output: Output:
{1=[{"value":"A"}], 2=[{"value":"B"}, {"value":"C"}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.