【问题标题】:How to convert nested loops to a one-liner? [duplicate]如何将嵌套循环转换为单线? [复制]
【发布时间】:2018-03-02 10:31:13
【问题描述】:

是否可以使用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

【问题讨论】:

  • 你的平面图是什么样子的?
  • 我对问题的更新是否回答了您的问题? @StefanBeike
  • questions.stream.flatMap(q -&gt; q.getAnswers().stream().map(ans -&gt; new QuestionAnswer(q.getLabel(), ans))).collect(Collectors.toList()) 可以吗?
  • 是的@VenkataRaju。您可以将其发布为答案,以便我接受。既然你是第一个发布它的人,我相信它是有效的。

标签: java java-stream nested-loops flatmap


【解决方案1】:

我认为:

question.forEach(q -> q.getAnswers().forEach(a -> questionAnswerCombinations.add(new QuestionAnswer(q.getLabel(), a)))

【讨论】:

  • 这不是使用 forEach 的有效答案,或者 for(value : values) 是相同的,并且 forEach 表示法的可读性较差。
  • 好吧,我同意它或多或少相同,不确定可读性,但问题是关于使用流api将循环转换为一行,并且响应是相关的。 (无论如何,只是想帮忙,如果有更好的方法,我会很乐意学习):)
  • 感谢您的回答,这是一个有效的单班轮,但我对映射解决方案很好奇。
【解决方案2】:

可能像下面这样可以帮助使用 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());

【讨论】:

    【解决方案3】:
    questions
        .stream
        .flatMap(qn -> qn.getAnswers()
                         .stream()
                         .map(ans -> new QuestionAnswer(qn.getLabel(), ans)))
        .collect(Collectors.toList())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 2013-11-29
      • 2023-02-15
      相关资源
      最近更新 更多