Java 如何将嵌套循环转换为单线循环?
是否可以使用Java 如何将嵌套循环转换为单线循环?,java,java-stream,nested-loops,flatmap,Java,Java Stream,Nested Loops,Flatmap,是否可以使用流api将下面的for循环转换为一个线性程序 List<QuestionAnswer> questionAnswerCombinations = new ArrayList<>(); for (Question question : questions) { for (String answer : question.getAnswers()) { questionAnswerCombinations.add(new Question
流
api将下面的for循环转换为一个线性程序
List<QuestionAnswer> questionAnswerCombinations = new ArrayList<>();
for (Question question : questions) {
for (String answer : question.getAnswers()) {
questionAnswerCombinations.add(new QuestionAnswer(question.getLabel(), answer ));
}
}
我认为:
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)); }); });
编辑:
或使用平面地图:
questionAnswerCombinations = questions.stream().flatMap(question -> question.getAnswers().stream().map(answer -> new QuestionAnswer(question.getLabel(), answer))).collect(Collectors.toList());
你的平面图看起来怎么样?我对这个问题的更新是否回答了你的问题@StefanBeike
questions.stream.flatMap(q->q.getAnswers().stream().map(ans->new QuestionAnswer(q.getLabel(),ans))).collect(Collectors.toList())
这行吗?是@VenkataRaju。你可以把它作为答案贴出来,这样我就可以接受了。因为你是第一个发布它的人,我相信它是有效的。这不是一个有效的答案,使用forEach或for(value:values)是相同的,并且forEach符号的可读性较差。好吧,我同意它或多或少是相同的,不确定可读性,但问题是关于使用流api在一行中转换循环,而回应是中肯的。(无论如何,我只是想帮你,如果有更好的方法,我很乐意学习):)谢谢你的回答,这是一个有效的一行,但我对映射解决方案很好奇。
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())