提示:本文为个人记录的Stream各种用法,写的不好地方多多谅解~持续更新中…
文章目录
1、list转map,并且去重,其中key和value都是具体字段值
例子:将用户list转为map
List<User> userList = userService.queryUserList();
Map<String, String> userMap= userList
.stream()
.collect(Collectors.toMap(User::getId, User::getId, (key1, key2)->key2));
注:key 冲突的解决办法,这里选择第二个key覆盖第一个key
2、一个list过滤掉另一个list的数据、两个List<T>取变量值相同的数据
final List<User> userList = userService.queryUserList();
Map<String, String> userMap = userList
.stream()
.collect(Collectors.toMap(User::getId, User::getId, (key1, key2)->key2));
final List<UserDTO> result= userList.stream()
.filter(each -> ObjectUtils.isNotEmpty(userMap .get(String.valueOf(each.getId()))))
.map(DO -> {
UserDTO dto = new UserDTO();
//若对象相同,可直接克隆,若不同可单独赋值,如 dto.setUserName(user.getUserName());
BeanUtils.copyProperties(DO, dto)
return dto;
}).collect(Collectors.toList());
注:这里克隆对象用的是sping下的BeanUtils.copyProperties()
3、分组后转map
根据部门编号分组,获取不同部门对应的人员
简单分组,key为指定字段,value为分组后的list
Map<String, List<User>> userMap = userList.stream().collect(Collectors.groupingBy(User::getDeptMentCode));
4、使用Stream流中的map方法用于字段类型转换,如List转换为Long数组
package Day12DemoStream;
import org.w3c.dom.ls.LSOutput;
import java.util.stream.Stream;
/*
Stream流中的常用方法_map:用于类型转换
如果需要将流中的元素映射到另一个流中,可以使用map方法.
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
该接口需要一个Function函数式接口参数,可以将当前流中的T类型数据转换为另一种R类型的流。
Function中的抽象方法:
R apply(T t);
*/
public class MapFunctionTest {
public static void main(String[] args) {
//获取一个String类型的Stream流
Stream<String> stream = Stream.of("1","2","3");
//使用map方法,把字符串类型的整数,转换(映射)为Integer类型的整数
Stream<Integer> stream1 = stream.map((String s)->{
return Integer.parseInt(s);
});
//遍历Stream1流
stream1.forEach((Integer i)-> System.out.print(i + " "));
}
}
或者:
将用户列表转换为用户id数组
Long[] userIdArray = userList.stream()
.collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
//此处是防止重复
new TreeSet<>(Comparator.comparing(UserDTO::getId))), ArrayList::new))
.stream().map((UserDTOeach)->{
return Long.valueOf(each.getId());
}).toArray(Long[]::new);
5、使用Stream流中的map方法将List转换为id列表
将用户列表转换为用户id数组
final List<Long> userIds = userList.stream().map(User::getId).collect(Collectors.toList())
6、stream将list转map,其中key为指定对象中的字段,value为对象
将用户list转为map,可根据key取出对应的用户数据做一些业务处理
List<User> userList = userService.queryUserList();
Map<String, User> userMap = userList
.stream()
.collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2)->key2));
7、提取list中,各个list并合并返回
获取部门列表下的所有用户,合并一个list返回
List<DeptMent> deptMentList = deptMentService.queryList();
List<User> userList = deptMentList.stream().flatMap(user-> user.getUserList().stream()).collect(Collectors.toList());