使用stream
api可以将下面的for循环转换为单行吗?
List<QuestionAnswer> questionAnswerCombinations = new ArrayList<>();
for (Question question : questions) {
for (String answer : question.getAnswers()) {
questionAnswerCombinations.add(new QuestionAnswer(question.getLabel(), answer ));
}
}
我虽然使用flatMap
,但是当我这样做时,我放松了question
。
将此嵌套循环转换为单行循环的正确方法是什么?
注意:如果需要,我可以添加Question
类的数据结构,但除了从用法中推断出的内容之外,没有任何复杂性。
更新:我要做的是将所有问题+答案组合收集到另一个列表中。如:
Question 1
-Answer a
-Answer b
-Answer c
Question 2
-Answer x
-Answer y
Question 1, Answer a
Question 1, Answer b
Question 1, Answer c
Question 2, Answer x
Question 2, Answer y
答案 0 :(得分:1)
我想:
question.forEach(q -> q.getAnswers().forEach(a -> questionAnswerCombinations.add(new QuestionAnswer(q.getLabel(), a)))
答案 1 :(得分:1)
下面的内容可能有助于使用 forEach 循环:
questions.stream().forEach(question -> {question.getAnswers().stream().forEach(answer -> { questionAnswerCombinations.add(new QuestionAnswer(question.getLabel(), answer)); }); });
<强>编辑:强>
或使用 flatMap :
questionAnswerCombinations = questions.stream().flatMap(question -> question.getAnswers().stream().map(answer -> new QuestionAnswer(question.getLabel(), answer))).collect(Collectors.toList());
答案 2 :(得分:1)
questions
.stream
.flatMap(qn -> qn.getAnswers()
.stream()
.map(ans -> new QuestionAnswer(qn.getLabel(), ans)))
.collect(Collectors.toList())