繁体   English   中英

嵌套集合lambda迭代

[英]Nested collections lambda iteration

假设我有一个包含集合的对象,所述集合上的每个元素都包含一个集合,每个集合都包含一个集合。

我想迭代最深的对象并将相同的代码应用于它。

必要的方法是微不足道的,但有没有办法让这一切变得简单?

以下是代码今天的样子:

My object o;
SecretType computedThingy = 78;
for (FirstLevelOfCollection coll : o.getList()) {
  for (SecondLevelOfCollection colColl : coll.getSet()) {
    for (MyCoolTinyObjects mcto : colColl.getFoo()) {
      mcto.setSecretValue(computedThingy);
    }
  }
}

我可以看到如何从最深的循环中创建一个lambda:

colColl.getFoo().stream().forEach(x -> x.setSecretValue(computedThingy)

但我可以做更多吗?

flatMap可用于此目的。 你在这里得到的是迭代各种最深集合的所有元素,就好像它们是一个集合:

o.getList().stream()
    .flatMap(c1 -> c1.getSet().stream())
    .flatMap(c2 -> c2.getFoo().stream())
    .forEach(x -> x.setSecretValue(computedThingy));

flatMap to rescue,带有嵌套String集合的简单示例

另请参见: Java 8 Streams FlatMap方法示例

使用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);

产生

foo 
bar 
another foo

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM