用 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);
相关文章