0

This question is a sort-of follow-up to Partition java streams in categories

I have a stream<A>, where

class A {
  String category();
  String data();
}

I would like to get a map<String, list<String>>, where the original stream is partitioned into sublists based on the value of category(), and then mapped to only extract the data(). 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 -> {xyz, zyx}
b -> {abc}
Community
  • 1
  • 1
Grzenio
  • 35,875
  • 47
  • 158
  • 240

1 Answers1

8

You need a slightly different groupBy

  stream.collect(Collectors.groupingBy(A::getCategory, 
         Collectors.mapping(A::data, Collectors.toList()));
Eugene
  • 117,005
  • 15
  • 201
  • 306