[英]Nested collections lambda iteration
Suppose I have an object containing a collection, each elements on the said collection contains a collection, and each collection contains a collection. 假设我有一个包含集合的对象,所述集合上的每个元素都包含一个集合,每个集合都包含一个集合。
And I want to iterate on the deepest objects and apply the same code to it. 我想迭代最深的对象并将相同的代码应用于它。
The imperative way is trivial, but is there a way to lambda-fy this all? 必要的方法是微不足道的,但有没有办法让这一切变得简单?
Here is how the code looks today: 以下是代码今天的样子:
My object o;
SecretType computedThingy = 78;
for (FirstLevelOfCollection coll : o.getList()) {
for (SecondLevelOfCollection colColl : coll.getSet()) {
for (MyCoolTinyObjects mcto : colColl.getFoo()) {
mcto.setSecretValue(computedThingy);
}
}
}
I can see how to make a lambda out of the deepest loop: 我可以看到如何从最深的循环中创建一个lambda:
colColl.getFoo().stream().forEach(x -> x.setSecretValue(computedThingy)
But can I do more? 但我可以做更多吗?
flatMap is available for such a purpose. flatMap可用于此目的。 What you get here is iteration over all elements of the various deepest collections as if they were a single collection:
你在这里得到的是迭代各种最深集合的所有元素,就好像它们是一个集合:
o.getList().stream()
.flatMap(c1 -> c1.getSet().stream())
.flatMap(c2 -> c2.getFoo().stream())
.forEach(x -> x.setSecretValue(computedThingy));
flatMap to the rescue, simple example with a nested collection of String flatMap to rescue,带有嵌套String集合的简单示例
See also: Java 8 Streams FlatMap method example 另请参见: Java 8 Streams FlatMap方法示例
Turn a List of Lists into a List Using Lambdas 使用Lambdas将列表列表转换为列表
Set<List<List<String>>> outerMostSet = new HashSet<>();
List<List<String>> middleList = new ArrayList<>();
List<String> innerMostList = new ArrayList<>();
innerMostList.add("foo");
innerMostList.add("bar");
middleList.add(innerMostList);
List<String> anotherInnerMostList = new ArrayList<>();
anotherInnerMostList.add("another foo");
middleList.add(anotherInnerMostList);
outerMostSet.add(middleList);
outerMostSet.stream()
.flatMap(mid -> mid.stream())
.flatMap(inner -> inner.stream())
.forEach(System.out::println);
Produces 产生
foo
bar
another foo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.