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 替换嵌套循环
基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
