Nested Lambda Iteration Collections

Suppose I have an object containing a collection, each item from the specified collection contains a collection, and each collection contains a collection.

And I want to iterate over the deepest objects and apply the same code to it.

The imperative is trivial, but is there a way lambda is all this?

Here's what the code looks like 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 see how to make lambda from the deepest loop:

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

But can I do more?

+4
source share
2 answers

flatMap for salvation, a simple example with a nested String collection

See also: Java 8 Streams FlatMap Method Example

Rotate list of lists to 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);

Gives out

foo 
bar 
another foo
+3

flatMap . , :

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

Source: https://habr.com/ru/post/1677177/


All Articles