用Java 8 flatmap替换嵌套循环

wvd*_*vdz 4 java loops java-8 java-stream flatmap

我正在尝试使用flatmap与Stream API进行嵌套循环,但我似乎无法弄明白.作为示例,我想重新创建以下循环:

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);
Run Code Online (Sandbox Code Playgroud)

我可以这样做,但这看起来很难看:

System.out.println("*** Nested Stream ***");
xs.stream().forEach(x ->
    ys.stream().forEach(y -> System.out.println(x + " + " + y))
);
Run Code Online (Sandbox Code Playgroud)

Flatmap看起来很有前景,但是如何在外部循环中访问变量?

System.out.println("*** Flatmap *** ");
xs.stream().flatMap(x -> ys.stream()).forEach(y -> System.out.println("? + " + y));
Run Code Online (Sandbox Code Playgroud)

输出:

*** 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
Run Code Online (Sandbox Code Playgroud)

Flo*_*own 11

您必须在flatMap舞台上创建所需的元素,例如:

xs.stream().flatMap(x -> ys.stream().map(y -> x + " + " + y)).forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)

  • @wvdz它始终取决于用例以及您更容易理解的内容。 (2认同)