我试图使用平台图来使用Stream创建一个嵌套的循环,但我似乎无法理解它。例如,我希望重新创建以下循环:
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);我可以这样做,但这看起来很丑:
System.out.println("*** Nested Stream ***");
xs.stream().forEach(x ->
ys.stream().forEach(y -> System.out.println(x + " + " + y))
);Flatmap看起来很有前途,但是如何访问外部循环中的变量呢?
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发布于 2016-11-18 14:02:09
您必须在flatMap阶段创建所需的元素,例如:
xs.stream().flatMap(x -> ys.stream().map(y -> x + " + " + y)).forEach(System.out::println);发布于 2016-11-18 14:19:15
通常,不需要flatMap
xs.forEach(x -> ys.stream().map(y -> x + " + " + y).forEach(System.out::println)); // X
xs.forEach(x -> ys.forEach(y -> System.out.println(x + " + " + y))); // V此外,这里也不需要Stream。
是的,它看起来很漂亮,但只有这样幼稚的任务。为每个元素创建/关闭一个新流,只会将它们合并到结果流中。所有这些都只是为了打印出来?
相反,forEach提供了一个不需要任何性能代价的单行解决方案(内部是一个标准foreach )。
发布于 2016-11-20 22:37:11
基本上,这是这些列表的笛卡儿积。我首先要把它们合并成一个清单:
List<String> xs = Arrays.asList(new String[]{ "one","two", "three"});
List<String> ys = Arrays.asList(new String[]{"four", "five"});
List<List<String>> input = Arrays.asList(xs, ys);然后创建一个列表流,每个列表都将映射到自己的流中,并将这些内容保存到Supplier中。
Supplier<Stream<String>> result = input.stream() // Stream<List<String>>
.<Supplier<Stream<String>>>map(list -> list::stream) // Stream<Supplier<Stream<String>>>然后减少这种供应商流,并为属于以下供应商的字符串流生产笛卡尔产品:
.reduce((sup1, sup2) -> () -> sup1.get().flatMap(e1 -> sup2.get().map(e2 -> e1 + e2)))还原返回是可选的,因此为了处理缺失的值,我将返回一个空字符串流:
.orElse(() -> Stream.of(""));毕竟,我们只需要获得供应商的值(这将是一个字符串流)并打印出来:
s.get().forEach(System.out::println);整个方法将如下所示:
public static void printCartesianProduct(List<String>... lists) {
List<List<String>> input = asList(lists);
Supplier<Stream<String>> s = input.stream()
// Stream<List<String>>
.<Supplier<Stream<String>>>map(list -> list::stream)
// Stream<Supplier<Stream<String>>>
.reduce((sup1, sup2) -> () -> sup1.get()
.flatMap(e1 -> sup2.get().map(e2 -> e1 + e2)))
.orElse(() -> Stream.of(""));
s.get().forEach(System.out::println);
}https://stackoverflow.com/questions/40678892
复制相似问题