java1.8 flatMap解析

jdk1.8 stream引入flatMap用于将stream扁平化处理。发部分例子都是string分割去重,比如hello和helloword分割后去重,

Arrays.asList("helloword", "hello").stream().map(t -> t.split("")).flatMap(t -> {

            return Arrays.asList(t).stream();

        }).forEach(System.out::println);

下面我们看一下flatMap实现原理:

flatMap源码为:


就像我上一篇文章关于stream源码讲解里面说的,首先它会生成一个op,用来opWrapSink,它的执行就是将传递过来的参数accept生成新的stream流,然后用于后续的froEach处理。

比如stream.flatMap(mapperFunction).filter(predicate1).forEach(consumer1);

执行过程为mapperFunction将遍历的参数生成新的stream,然后依次遍历当前的stream执行余下的sinkChain。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容