[英]Java 8 Stream API equivalent of nested for loops
Is it possible to replace the processing performed in this example with a single Java8 Stream API instruction, instead of nested for loops ? 是否可以用单个Java8 Stream API指令代替嵌套的for循环来代替在本示例中执行的处理?
public static void main(String[] args) {
List<BeanA> aList = Arrays.asList(new BeanA(), new BeanA(), new BeanA());
List<BeanB> bList = Arrays.asList(new BeanB(), new BeanB(), new BeanB());
List<Bean> result = new ArrayList<>();
for (BeanA a : aList) {
for (BeanB b : bList) {
result.add(new Bean(a, b));
}
}
System.out.println("size:" + result.size());
System.out.println("result:" + result);
}
public static class BeanA {
}
public static class BeanB {
}
public static class Bean {
private BeanA a;
private BeanB b;
public Bean(BeanA a, BeanB b) {
this.a = a;
this.b = b;
}
}
You can do it with Stream
s, but even with Stream
s you can't avoid the nested iteration, since you want to produce aList.size() * bList.size()
instances of Bean
. 你可以做到这一点Stream
S,但即使Stream
是你无法避免嵌套迭代,因为要产生aList.size() * bList.size()
的实例Bean
。
List<Bean> result =
aList.stream()
.flatMap(a->bList.stream().map(b->new Bean(a,b)))
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.