Java8之map和flatMap

以前有点搞不懂这两个概念,今天在scala里面看到flatMap是等于map+flatten,把它扁平化的感觉。

就想用Java试一下,确实是降低维度,把它打平的感觉。

官方的一个解释:

map:Returns a stream consisting of the results of applying the given function to the elements of this stream.

返回一个流,包含给定函数应用在流中每一个元素后的结果

flatmap:Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

返回一个流,包含将此流中的每个元素替换为通过给定函数映射应用于每个元素而生成的映射流的内容

来一段代码瞅瞅,造一下数据

        List<List<String>> res = new ArrayList<>();
        List<String> list = new ArrayList<>();
        for (int i = 1; i < 4; i++) {
            list.add(i + "");
        }
        List<String> list2 = new ArrayList<>();
        for (int i = 1; i < 5; i++) {
            list2.add(i + "");
        }

        res.add(list);
        res.add(list2);

        List<Stream<String>> collect1 = res.stream().map((li -> li.stream().map(s -> s + "处理"))).collect(Collectors.toList());
        List<String> collect2 = res.stream().flatMap(li -> li.stream().map(s -> s + "处理")).collect(Collectors.toList());
       

看结果:

用Debug设置断点

发现:

collect1有两层了,而collect2只有一层了,数据都在这一层下面。

用了flatMap确实降低了维度。只有一层了!觉得通俗易懂的给点个赞呗!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值