Partition java streams in categories [duplicate]

2019-02-17 15:35发布

问题:

This question already has an answer here:

  • Java 8 List<V> into Map<K, V> 19 answers

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));