Partition java streams in categories [duplicate]

假装没事ソ 提交于 2019-12-30 09:28:10

问题


I have a stream<A>, where

class A {
  String category();
  // ...
}

I would like to get a map<String, list<A>>, where the original stream is partitioned into sublists based on the value of category(). It is pretty trivial to have it implemented using a for loop, but is it possible to get a more elegant solution harnessing java streams?

EXAMPLE:

Given {[a, xyz], [a, zyx], [b, abc]}, I would like to get a map:

a -> {[a, xyz], [a, zyx]}
b -> {[b, abc]}

回答1:


Use the groupingBy collector.

stream.collect(Collectors.groupingBy(A::category));



来源:https://stackoverflow.com/questions/43609324/partition-java-streams-in-categories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!