java8的stream中的map和forEach方法的区别

  1. forEach的错误使用方式:(又重新赋值了)
List<Student> studentChangeList = studentList.stream().forEach(student -> student.setAge(99));

报错!!!因为 ForEach 处理过的 Stream 是没有返回值的,它是void类型,所以ForEach 之后再赋值给 studentChangeList 没有做强制类型转换,报错。

forEach的正确打开方式:(没有重新赋值)
但是现在就是需要对集合进行处理,并获取处理过的集合数据,可以这样写

studentList.stream().forEach(student -> student.setAge(99));

studentList 中的数据就是已经处理过的数据。

map() 是1对1映射

  1. map方法有返回值
  2. map方法调用完之后,如果需要得到一个list类型的结果,必须这样有.collect(Collectors.toList()):
List<User> users = userList.stream()
.map(item -> item.getAge() + 20)
.collect(Collectors.toList());
// 这里有.collect(Collectors.toList())

forEach() 是遍历list中的所有元素并做处理

虽然 ForEach 处理 Stream 中元素的时候没有返回值,但是 ForEach 对 Stream 中元素已经产生影响,即 ForEach 对 Stream 中元素的操作已经被保存下来。

userList.stream().forEach(item -> {
	item.setAge(18);
	item.setName("我的名字被改变了!");
});
// 这里没有.collect.(Collectors.toList()) 
// 因为forEach()本来就是遍历的意思,遍历完之后原list中的元素已经被改变了

总结

当只是使用一下list中的元素的时候,用map;当需要改变list中的元素值的时候,用forEach

  1. map() 有返回值,还是原来的链表或者set的类型;
    返回的时候需要用.collect(Collectors.toList());
    只是起到映射作用,不会对原来的list中的元素做出任何改变
  2. forEach()无返回值
    不需要.collect(Collectors.toList());
    会改变原来的list中的元素

例子

// 先forEach 然后map
users.getList().forEach(l -> {
	List<OdiRole> odiUserRoles = userRoleService.getUserRole(l.getId());
	l.setRoleNames(odiUserRoles.stream().map(OdiRole::getName).collect(Collectors.joining(",")));
});
// PageHelper分页方式1   new PageInfo(tSolutionList) 
public PageInfo<TSolution> queryTSolutionList(TSolution tSolution) {
    List<TSolution> tSolutionList = tSolutionMapper.selectTSolutionList(tSolution);
    PageHelper.startPage(0, 10);
    PageInfo pageInfo = new PageInfo(tSolutionList);
    return pageInfo;
}

// PageHelper分页方式2    doSelectPageInfo()
public PageInfo<TSolution> querySolutionSportalList(TSolution tSolution) {
    return PageHelper.startPage(0, 10).doSelectPageInfo(() -> tSolutionMapper.querySportalTSolutionList(tSolution));
}
  • 15
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值