【问题标题】:flatMap triple nested streamsflatMap 三重嵌套流
【发布时间】:2021-11-25 04:00:30
【问题描述】:

我正在尝试 flatMap 并从三个列表中获取字符串列表的结果。我以某种方式能够通过以下代码做到这一点。代码正在运行,但不知何故我觉得我把它弄得太复杂了。有人可以给我一些建议,可以更好地改进它

countries.stream()
    .map(country -> titles.stream()
        .map(title -> games.stream()
            .map(game -> Arrays.asList(game, country + "_" + title + "_" + game))
            .collect(toList()))
        .collect(toList()))
    .collect(toList())
    .stream()
    .flatMap(Collection::stream)
    .flatMap(Collection::stream)
    .flatMap(Collection::stream)
    .collect(Collectors.toSet());

为了澄清逻辑,传统方法如下所示:

Set<List<String>> results = new HashSet<>();
for (String country : countries) {
    for (String title : titles) {
        for (String game : games) {
            results.add(Arrays.asList(game, country + "_" + title + "_" + game));
        }
    }
}

【问题讨论】:

  • 顺便说一句,更喜欢List.of 而不是Arrays.asList(除非你低于Java 9)。

标签: java java-stream nested-loops flatmap


【解决方案1】:

您可以分两步完成:

首先创建国家和标题列表的串联:

List<String> countriesTitle = countries.stream()
            .flatMap(country -> titles.stream()
                    .map(title -> country + "_" + title))
            .collect(Collectors.toList());

然后根据之前的结果创建连接列表country+"_"+title+"_"+game字符串:

Stream.concat(games.stream(),
                    games.stream()
                          .flatMap(game -> countriesTitle.stream()
                                .map(countryTitle -> countryTitle + "_" + game)))
         .collect(Collectors.toList());

更新答案:

games.stream()
      .flatMap(game -> countries.stream()
               .flatMap(country -> titles.stream()
                   .flatMap(title -> Stream.of(game, country + "_" + title + "_" + game))))
       .collect(Collectors.toSet());

【讨论】:

  • 感谢您的回复,为我犯的一个错误道歉......实际上 ArrayList 中的第一项是game 而不是country+"_"+title
  • @Alex Man 更新了它。
  • 我觉得少了点什么
  • 我没明白它的意思?最后你把它们弄平。对吗?
猜你喜欢
  • 2016-02-08
  • 2020-08-22
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 2011-12-01
相关资源
最近更新 更多