用Java 8 flatmap替换嵌套循环 [英] Replace nested loop with Java 8 flatmap

查看:284
本文介绍了用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 stage,like:

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替换嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆