我有一个Answers实体,其值是这样的
question answer
1 x
2 y
3 z
4 p
1 x
2 q
3 r
我需要按问题分组回答
Map<Integer, List<String>>
<1, [x,x]
2, [y,p]
3, [z,r]
4, [p]>
我可以这样得到List<Answer>
Map<Integer, List<Answer>> collect = answers
.stream()
.collect(Collectors.groupingBy(Answer::getQuestion));
但是我找不到一种将其作为List<String>
而非List<Answer>
的方式吗?
答案 0 :(得分:5)
Map<Integer, List<String>> collect = answers
.stream()
.collect(Collectors.groupingBy(
Answer::getQuestion,
Collectors.mapping(Answer::getAnswerAsString, Collectors.toList())
));
只需将getAnswerAsString
替换为可以从Answer
获得该String的任何方法即可。
答案 1 :(得分:3)
您可以这样做
Map<Integer, List<String>> collect = answers.stream()
.collect(Collectors.groupingBy(Answer::getQuestion,
Collectors.mapping(Answer::getAnswer, Collectors.toList())));