集合转 Map (key 存在重复)
当集合中 id 会存在重复时,上面那种方式会报错,此时需要指定重复时选用哪一个 value
Map map = list.stream().collect(Collectors.toMap(ReviewerRest::getId, x -> x, (before, after) -> after));
复制代码
集合转 Map (value 存在 null 值)
当 value 存在 null 值时上面那种方式会报错,此时需要换一种写法
Map map = list.stream().collect(HashMap::new, (mapItem, item) -> mapItem.put(item.getId(), item.getDate()), HashMap::putAll);
复制代码
集合分组 转 Map
Map> map = list.stream().collect(Collectors.groupingBy(ReviewerRest::getId));
复制代码
集合分区 转 Map
Map> map = list.stream().collect(Collectors.partitioningBy(r -> r.getRest() == 1));
复制代码
集合分组个数统计
Map map = list.stream().collect(Collectors.groupingBy(ReviewerRest::getId,Collectors.counting()));
复制代码
集合分组转某个属性集合
Map> map = list.stream().collect(Collectors.groupingBy(ReviewerRest::getId,Collectors.mapping(ReviewerRest::getRest,Collectors.toList())));
复制代码
集合分组聚合查询最大元素
Map> map = list.stream().collect(Collectors.groupingBy(ReviewerRest::getReviewerId, Collectors.maxBy(Comparator.comparing(ReviewerRest::getDate))));
复制代码
集合分组聚合求和
//目前只支持 int、double、long
Map map = list.stream().collect(Collectors.groupingBy(ReviewerRest::getReviewerId, Collectors.summingLong(
java8采用stream对集合的常用操作
User :{
id,
name,
age
}
1.对象集合的分组(有两种形式)
示例:List userList,根据id分组,可以分组成为两种格式的map
(1)Map
Map map = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
(2)Map
Map> = userList.stream().collect(Collectors.groupingBy(User::getId));
2.去重操作
对List 实现去重,distinct关键字
示例:userList= userList.stream().distinct().collect(Collectors.toList());
3.stream的map
主要用于得到特定的结构
例如:List userList,我向得到User Id的集合
List idList = userList.stream.map(User::getId).collect(Collectors.toList());
4.stream的filter
主要用于数据的筛选。
例1:一个条件的筛选,删选id>5的User
List userList = userList.stream.filter(i->i.getId()>5).collect(Collectors.toList());
例2:两个条件的删选用&&连接就行,删选id>5年纪>10的User
List userList = userList.stream.filter(i->i.getId()>5&&i.getAge()>10).collect(Collectors.toList());
5.用来作循环
userList.stream().forEach(user -> System.out.println("姓名:" + user.getName()));
当然也可以加个limit限制数量