【发布时间】: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