- 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映射
- map方法有返回值
- 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
- map() 有返回值,还是原来的链表或者set的类型;
返回的时候需要用.collect(Collectors.toList());
只是起到映射作用,不会对原来的list中的元素做出任何改变 - 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));
}