flatMap 三重嵌套流

flatMap triple nested streams

我正在尝试 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<String> countriesTitle = countries.stream()
            .flatMap(country -> titles.stream()
                    .map(title -> country + "_" + title))
            .collect(Collectors.toList());

然后根据之前的结果创建串联列表country+"_"+title+"_"+game string:

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());