Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use group by to get a list of new column in an entity

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>?

like image 932
user1298426 Avatar asked Jan 28 '23 00:01

user1298426


2 Answers

 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.

like image 57
Eugene Avatar answered Jan 29 '23 12:01

Eugene


You may do it like so,

Map<Integer, List<String>> collect = answers.stream()
    .collect(Collectors.groupingBy(Answer::getQuestion, 
        Collectors.mapping(Answer::getAnswer, Collectors.toList())));
like image 40
Ravindra Ranwala Avatar answered Jan 29 '23 14:01

Ravindra Ranwala