嵌套集合lambda迭代 [英] Nested collections lambda iteration

查看:62
本文介绍了嵌套集合lambda迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想遍历最深的对象,并对其应用相同的代码.

当务之急是微不足道的,但是有没有办法让所有这些事情变得f昧?

以下是今天的代码:

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)

但是我还能做更多吗?

解决方案

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

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:

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

But can I do more?

解决方案

flatMap to the rescue, simple example with a nested collection of String

See also: Java 8 Streams FlatMap method example

Turn a List of Lists into a List Using 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

这篇关于嵌套集合lambda迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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