Java-Stream-flatMap


  Leave leave1 = new Leave("1","1",new Date(),CollUtil.newArrayList("A","B"));
  Leave leave2 = new Leave("2","2",new Date(),CollUtil.newArrayList("C","D"));
  Leave leave3 = new Leave("3","3",new Date(),CollUtil.newArrayList("E","F"));
  ArrayList leaves = CollUtil.newArrayList(leave1, leave2, leave3);

对于上述代码,如果我想取出第4个参数的集合如何处理呢?在flatMap之前,我所能想到的就是暴力的遍历吧,如下:

List resultList = new ArrayList<>();
for (Leave leaf : leaves) {
    resultList.addAll(leaf.getNameList());
}

这样就将所有的nameList放入一个集合中,但是如果我想用stream流呢?在未了解flatMap前,我可能会用Map,但是map有个问题在于,我想要一个集合,但是Map会生产集合嵌套集合,代码如下:

List> resultList = leaves.stream().map(Leave::getNameList).collect(Collectors.toList());

如果我既想用stream,又想要List resultList呢?flatMap闪亮登场:

 List resultList = leaves.stream()
.flatMap(leave
-> leave.getNameList().stream())
.collect(Collectors.toList());
public static void main(String[] args) {
        ArrayList strings1 = CollUtil.newArrayList("123", "212", "212");
        ArrayList strings2 = CollUtil.newArrayList("abc", "qwe", "qbc");
        List collect = Stream.of(strings1,strings2).flatMap(Collection::stream).collect(Collectors.toList());
}

以上flatMap是将相同类型元素合并到一起,既然能合并到一起,那flatMap能不能将一起的元素拆分开呢?以下是将元素进行拆分:

 ArrayList list = CollUtil.newArrayList("ABC", "DEF", "GHI");
 List collect = list.stream().flatMap(ele -> Stream.of(ele.split(""))).collect(Collectors.toList());