2017-05-15 117 views
4

假设我有一个包含集合的对象,上述集合中的每个元素都包含一个集合,并且每个集合都包含一个集合。嵌套集合lambda迭代

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

命令式的方式是微不足道的,但有没有办法让lambda-fy这一切?

这是怎样的代码看起来今天:

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) 

但我可以做多吗?

回答

3

flatMap救援,简单的例子有字符串的嵌套集合

参见: 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); 

主要生产

foo 
bar 
another foo 
5

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

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

有'Collectors.flatMapping'在JDK-9还... – Eugene