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<Leave> leaves = CollUtil.newArrayList(leave1, leave2, leave3);

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

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

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

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

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

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

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

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

 

posted @ 2022-06-13 20:15  佛祖让我来巡山  阅读(225)  评论(0编辑  收藏  举报

佛祖让我来巡山博客站 - 创建于 2018-08-15

开发工程师个人站,内容主要是网站开发方面的技术文章,大部分来自学习或工作,部分来源于网络,希望对大家有所帮助。

Bootstrap中文网