Nested collections lambda iteration

tisek :

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?

Viktor Mellgren :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=476677&siteId=1