Replace nested loop with Java 8 flatmap(用 Java 8 flatmap 替换嵌套循环)
问题描述
我正在尝试使用 flatmap 通过 Stream API 创建一个嵌套循环,但我似乎无法弄清楚.例如,我想重新创建以下循环:
I'm trying to use flatmap to make a nested loop with the Stream API, but I can't seem to figure it out. As an example, I want to recreate the following loop:
List<String> xs = Arrays.asList(new String[]{ "one","two", "three"});
List<String> ys = Arrays.asList(new String[]{"four", "five"});
System.out.println("*** Nested Loop ***");
for (String x : xs)
for (String y : ys)
System.out.println(x + " + " + y);
我可以这样做,但这看起来很丑:
I can do it like this, but this seems ugly:
System.out.println("*** Nested Stream ***");
xs.stream().forEach(x ->
ys.stream().forEach(y -> System.out.println(x + " + " + y))
);
Flatmap 看起来很有希望,但我如何才能访问外循环中的变量?
Flatmap looks promising, but how can I access the variable in the outer loop?
System.out.println("*** Flatmap *** ");
xs.stream().flatMap(x -> ys.stream()).forEach(y -> System.out.println("? + " + y));
输出:
*** Nested Loop ***
one + four
one + five
two + four
two + five
three + four
three + five
*** Nested Stream ***
one + four
one + five
two + four
two + five
three + four
three + five
*** Flatmap ***
? + four
? + five
? + four
? + five
? + four
? + five
推荐答案
你必须在 flatMap
阶段创建你想要的元素,比如:
You have to create your desired elements in the flatMap
stage, like:
xs.stream().flatMap(x -> ys.stream().map(y -> x + " + " + y)).forEach(System.out::println);
这篇关于用 Java 8 flatmap 替换嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用 Java 8 flatmap 替换嵌套循环
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01