一. stream将list转化为map
在Stream流中将List转换为Map,是使用Collectors.toMap方法来进行转换。
1.key和value都是对象中的某个属性值。
Map<String, String>userMap1=userList.stream().collect(Collectors.toMap(User::getId, User::getName));
2.key是对象中的某个属性值,value是对象本身(使用返回本身的lambda表达式)。
Map<String, User>userMap2=userList.stream().collect(Collectors.toMap(User::getId, User ->User));
3.key是对象中的某个属性值,value是对象本身(使用Function.identity()的简洁写法)。
Map<String, User>userMap3=userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
4.key是对象中的某个属性值,value是对象本身,当key冲突时选择第二个key值覆盖第一个key值。
Map<String, User>userMap4=userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(oldValue, newValue)->newValue));
如果不正确指定Collectors.toMap方法的第三个参数(key冲突处理函数),那么在key重复的情况下该方法会报出【Duplicate Key】的错误导致Stream流异常终止,使用时要格外注意这一点。
jdk8Stream tomap 存在bug,value为null是会报错空指针:
1.list转map 当map的value值为空时会报错空指针异常,有以下两种处理方式:
//解决方案一,使用Optional类处理null
HashMap<String, String> cityProvinceMap = cityProvinceList.stream().collect(Collectors.toMap(s -> Optional.ofNullable(s.getCityName()).orElse(null), s -> Optional.ofNullable(s.getProvince()).orElse("unknown"), (a, b) -> b, HashMap::new));
//解决方案二,直接使用collect()方法进行规约操作
HashMap<String, String> cityProvinceMap2 = cityProvinceList.stream().collect(HashMap::new, (map, item) -> map.put(item.getCityName(), item.getProvince()), HashMap::putAll);
2.list空字段排序:
if("asc".equals(bo.getOrderType())){
orderList = orderList.stream().sorted(Comparator.comparing(CompanyListingStatisticsModel::getPeTtm, Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());
}else{
orderList = orderList.stream().sorted(Comparator.comparing(CompanyListingStatisticsModel::getPeTtm, Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
}
————————————————
版权声明:本文为CSDN博主「大脸猫-」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_36937152/article/details/125885899
二. grouppingby,它可以非常迅速的将实体类中的中数据进行分组获取。
举例:
//a 从一个实体类为TestDTO1的list中获取level1CategoryId这个属性与它对应的pitemId的List的Map
Map<Long,List<Long>> exhibitionPitemMap = list.stream().collect(Collectors.groupingBy(TestDTO1::getLevle1CategoryId, Collectors.mapping(TestDTO1::getPitemId, Collectors.toList())));
//b level1CategoryId将原有的list进行分组成这个level1CategoryId以及他的List<TestDTO2>集合Map
Map<Long, List<TestDTO2>> categoryPitemMap = list.stream().collect(Collectors.groupingBy(TestDTO2::getLevle1CategoryId));
三.排序
list = list.stream()
.sorted(Comparator.comparing(Test::getAge).reversed())
.collect(Collectors.toList());
list.forEach(System.out::println);
说明:Comparator.comparing(放实体类名称::放列名):添加排序字段;
reversed():倒序。
collect(Collectors.toList()):转成集合。
list.forEach(System.out::println):打印循环。
四. filter
使用Java 8的新特性后,我们可以使用 stream.filter()来过滤 List,使用 .findAny().orElse (null) 来返回指定的对象.直接上代码
Person result1 = collection.stream() // 转化为流
.filter(x -> "张三".equals(x.getName())) // 只过滤出"张三"
.findAny() // 如果找到了就返回
.orElse(null); // 如果找不到就返回null
System.out.println(result1);