Java 8 Stream操作汇总
目录前提条件:
// User实体类
@Data
public class User {
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private Integer age;
/**
* 性别 1-男 2-女
*/
private Integer sex;
/**
* 身高
*/
private Long height;
/**
* 体重
*/
private Double weight;
/**
* 体重
*/
private BigDecimal money;
}
// 获取用户列表
public static List<User> getUserList() {
User user1 = new User("小王", 18, 1,180L,60D, BigDecimal.valueOf(2000L));
User user2 = new User("小红", 17, 2,170L,55D, BigDecimal.valueOf(1000L));
User user3 = new User("小张", 19, 1,160L,50D, BigDecimal.valueOf(3000L));
User user4 = new User("小蓝", 16, 2,150L,51D, BigDecimal.valueOf(4000L));
return new ArrayList<>(Arrays.asList(user1, user2, user3, user4));
}
1.分组
要求:按性别分组
List<User> userList = getUserList();
Map<Integer, List<User>> collect = userList.stream()
.filter(e -> e.getSex() != null)
.collect(Collectors.groupingBy(User::getSex));
.collect(Collectors.groupingBy(User::getSex, Collectors.counting()));
/**
Result: key=1 value=[user1,user3]
key=2 value=[user2,user4]
**/
注意:分组字段(sex)不能为null,如果存在null会出现:element cannot be mapped to a null key
错误
2.分组统计
要求:统计不同性别人员个数
Map<Integer, Long> collect1 = userList.stream()
.filter(e -> e.getSex() != null)
.collect(Collectors.groupingBy(User::getSex, Collectors.counting()));
/**
Result: key=1 value=2
key=2 value=2
**/
3.分组求和
要求:统计不同性别人员年龄之和
Map<Integer, Integer> collect = userList.stream()
.filter(e -> e.getSex() != null)
.collect(Collectors.groupingBy(User::getSex, Collectors.summingInt(User::getAge)));
/**
Result: key=1 value=37
key=2 value=33
**/
注意:
- 分组求和时,所调用的方法与求和字段有关,如 年龄字段类型为
Integer
,对应Collectors.summingInt(User::getAge)
Integer 类型 ==> Collectors.summingInt(User::getAge)
Double 类型 ==> Collectors.summingDouble(User::getWeight)
Long 类型 ==> Collectors.summingLong(User::getHeight)
Bigdecimal 类型 ==> Collectors.reducing(BigDecimal.ZERO, User::getMoney, BigDecimal::add)
eg. userList.stream()
.filter(e -> e.getSex() != null)
.collect(Collectors.groupingBy(User::getMoney, Collectors.reducing(BigDecimal.ZERO, User::getMoney, BigDecimal::add)));
4.最大最小值
要求:查询年龄最大最小的用户
// 最大
User user = userList.stream().max(Comparator.comparingInt(User::getAge)).get();
// 最小
User user = userList.stream().min(Comparator.comparingInt(User::getAge)).get();
5.排序
要求:按年龄排序
// sort默认为升序(从小到大)
List<User> collect = userList.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
// 降序排序
List<User> collect = userList.stream()
.sorted(Comparator.comparing(User::getAge,Collections.reverseOrder()))
.collect(Collectors.toList());
标签:Java,Stream,Collectors,userList,汇总,collect,User,getSex,BigDecimal
From: https://www.cnblogs.com/XiaoMingStudy1/p/16903523.html