Nested collections lambda iteration

天涯浪子 提交于 2021-02-07 07:36:35

问题


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?


回答1:


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



回答2:


flatMap is available for such a purpose. 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));


来源:https://stackoverflow.com/questions/43981669/nested-collections-lambda-iteration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!