Java 8 stream流之flatMap

时间:2025-01-21 07:37:09
        Leave leave1 = new Leave("1","1",new Date(),("A","B"));
        Leave leave2 = new Leave("2","2",new Date(),("C","D"));
        Leave leave3 = new Leave("3","3",new Date(),("E","F"));
        ArrayList<Leave> leaves = (leave1, leave2, leave3);

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

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

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

List<List<String>> resultList = ().map(Leave::getNameList).collect(());

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

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

以上flatMap是将相同类型元素合并到一起,既然能合

并到一起,那flatMap能不能将一起的元素拆分开呢?以下是将元素进行拆分:

        ArrayList<String> list = ("ABC", "DEF", "GHI");
        List<String> collect = ().flatMap(ele -> ((""))).collect(());