如何将嵌套循环转换为单行循环?
How to convert nested loops to a one-liner?
是否可以使用 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
class 的数据结构,但除了从用法中推断出的内容外,没有任何并发症.
更新: 我想做的基本上是将所有问题+答案组合收集到另一个列表中。如:
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
我认为:
question.forEach(q -> q.getAnswers().forEach(a -> questionAnswerCombinations.add(new QuestionAnswer(q.getLabel(), a)))
可能像下面这样的东西可以帮助使用 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());
questions
.stream
.flatMap(qn -> qn.getAnswers()
.stream()
.map(ans -> new QuestionAnswer(qn.getLabel(), ans)))
.collect(Collectors.toList())
是否可以使用 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
class 的数据结构,但除了从用法中推断出的内容外,没有任何并发症.
更新: 我想做的基本上是将所有问题+答案组合收集到另一个列表中。如:
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
我认为:
question.forEach(q -> q.getAnswers().forEach(a -> questionAnswerCombinations.add(new QuestionAnswer(q.getLabel(), a)))
可能像下面这样的东西可以帮助使用 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());
questions
.stream
.flatMap(qn -> qn.getAnswers()
.stream()
.map(ans -> new QuestionAnswer(qn.getLabel(), ans)))
.collect(Collectors.toList())