java8中stream的map和foreach区别

1. stream().map()
示例:对List中的每个数字取平方

public void testMap() {
    List<Integer> test = Arrays.asList(1,2,3,4,5);
    List<Integer> collect = test.stream()
            .map(i->func(i))
            .collect(Collectors.toList());
    log.info("collect is " +collect);
    log.info("test is " + test);
}

private int func(int i) {
	return i*i;
}

输出结果:
collect is [1, 4, 9, 16, 25]
test is [1, 2, 3, 4, 5]

可见,map会将stream中的每个数字(1,2,3,4,5)送入函数(func)执行后,将原来的数字替换成了新的函数运算结果。所以map执行完,stream中的内容已经从(1,2,3,4,5)变成了 (1, 4, 9, 16, 25)。当然了,原List test的内容是没有变的。

2. stream().foreach()
依旧取平方

    public void testForeach() {
        List<Integer> test = Arrays.asList(1,2,3,4,5);
        test.stream().forEach(i->func(i));
        log.info("test is " + test);
    }

    private int func(int i) {
        return i*i;
    }

输出结果
test is [1, 2, 3, 4, 5]

foreach是一个stream的结尾,不像map后还能用collect,foreach之后stream就被消耗完了。foreach就是单纯地把数字送进func执行,就没有然后了,也不再返回什么。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值