I have Answer entity which has values like this
question answer
1 x
2 y
3 z
4 p
1 x
2 q
3 r
I need to get answers group by questions
Map<Integer, List<String>>
<1, [x,x]
2, [y,p]
3, [z,r]
4, [p]>
I could get List<Answer>
like this
Map<Integer, List<Answer>> collect = answers
.stream()
.collect(Collectors.groupingBy(Answer::getQuestion));
but I can't find a way to get it as List<String>
rather than List<Answer>
?
Map<Integer, List<String>> collect = answers
.stream()
.collect(Collectors.groupingBy(
Answer::getQuestion,
Collectors.mapping(Answer::getAnswerAsString, Collectors.toList())
));
just replace getAnswerAsString
with whatever method you have that gets you that String from Answer
.
You may do it like so,
Map<Integer, List<String>> collect = answers.stream()
.collect(Collectors.groupingBy(Answer::getQuestion,
Collectors.mapping(Answer::getAnswer, Collectors.toList())));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With