Java 集合stream流操作示例详解
自java 8 版本起推出集合stream流操作特性,确实非常方便的对list进行各种操作,告别使用for的时代来了。下面总结了一些常用的对List对象进行遍历、过滤、查询、去重、排序、分组、提取等操作示例,;
@Data
public class User{
private Integer id;
private String name;
private String sex;
private Integer age;
private String department;
private BigDecimal salary;
public User(){
}
public User(Integer id,String name,String sex,Integer age,String department,BigDecimal salary){
this.id=id;
this.name=name;
this.sex=sex;
this.age=age;
this.department=department;
this.salary=salary;
}
}
public class ListStream{
public static void main(String [] args){
List<User> userList = getUserList();
}
public static List<User> getUserList(){
List<User> userList = new ArrayList<User>();
userList.add(new User(1, "黄文隆", "男", 32, "研发部", BigDecimal.valueOf(3600)));
userList.add(new User(2, "江奕云", "男", 30, "财务部", BigDecimal.valueOf(3800)));
userList.add(new User(3, "刘姿婷", "女", 20, "人事部", BigDecimal.valueOf(3700)));
userList.add(new User(4, "夏志豪", "男", 38, "研发部", BigDecimal.valueOf(3500)));
userList.add(new User(5, "林雅南", "女", 25, "财务部", BigDecimal.valueOf(3200)));
return userList;
}
}
现在我们有一个List类型的列表,可以使用Java8的stream流对它进行遍历、过滤、查询、去重、排序、分组等操作。
遍历
userList.forEach(System.out::println);
过滤
通过filter()进行数据筛选过滤。
//获取部门为“研发部”的用户列表
userList = userList.stream().filter(user -> user.getDepartment() == "研发部").collect(Collectors.toList());
查询
//获取组织编号为“黄文隆”的组织信息,如果没有找到则返回null
User user = userList.stream().filter(u -> u.getName().equals("黄文隆")).findAny().orElse(null);
去重
使用 distinct() 方法可以去除重复的数据。
//获取部门列表,并去除重复数据
List<String> departmentList = userList.stream().map(User::getDepartment).distinct().collect(Collectors.toList());
排序
使用sorted()方法进行数据排序
//根据年龄排序(升序)
userList = userList.stream().sorted((u1, u2) -> u1.getAge() - u2.getAge()).collect(Collectors.toList());
//推荐:userList = userList.stream().sorted(Comparator.comparingInt(User::getAge)).collect(Collectors.toList());
//降序:userList = userList.stream().sorted(Comparator.comparingInt(User::getAge).reversed()).collect(Collectors.toList());
分组
使用 groupingBy() 将数据进行分组,最终返回一个 Map 类型。
//根据部门对用户列表进行分组
Map<String,List<User>> userMap = userList.stream().collect(Collectors.groupingBy(User::getDepartment));
//根据部门和性别对用户列表进行分组
Map<String,Map<String,List<User>>> userMap = userList.stream().collect(Collectors.groupingBy(User::getDepartment,Collectors.groupingBy(User::getSex)));
//根据部门进行分组,汇总各个部门用户的平均年龄
Map<String, Double> userMap = userList.stream().collect(Collectors.groupingBy(User::getDepartment, Collectors.averagingInt(User::getAge)));
提取
使用 map() 方法获取用户列表中的名称列。
//获取用户名称列表
List<String> nameList = userList.stream().map(User::getName).collect(Collectors.toList());
//或者:List<String> nameList = userList.stream().map(user -> user.getName()).collect(Collectors.toList());
判断(查找)
//判断用户列表中是否存在名称为“黄文隆”的数据
boolean result1 = userList.stream().anyMatch(user -> user.getName().equals("name_01"));
//判断用户名称是否都包含“黄”字段
boolean result2 = userList.stream().allMatch(user -> user.getName().contains("黄"));
//判断用户名称是否存在不包含“黄”字段
boolean result3 = userList.stream().noneMatch(user -> user.getName().contains("黄"));
统计
//用户列表中年龄的最大值、最小值、总和
int maxVal = userList.stream().map(User::getAge).reduce(Integer::max).get();
int minVal = userList.stream().map(User::getAge).reduce(Integer::min).get();
int sumVal = userList.stream().map(User::getAge).reduce(0,Integer::sum);
//用户列表中年龄的最大值、最小值、总和、平均值
int maxVal = userList.stream().mapToInt(User::getAge).max().getAsInt();
int minVal = userList.stream().mapToInt(User::getAge).min().getAsInt();
int sumVal = userList.stream().mapToInt(User::getAge).sum();
double aveVal = userList.stream().mapToInt(User::getAge).average().getAsDouble();
//统计研发部的人数,使用 counting()方法进行统计
Long departCount = userList.stream().filter(user -> user.getDepartment() == "研发部").collect(Collectors.counting());
//统计30岁以上的人数,使用 count()方法进行统计(推荐)
Long ageCount = userList.stream().filter(user -> user.getAge() >= 30).count();
//统计薪资大于1500元的人数
Long salaryCount = userList.stream().filter(user -> user.getSalary().compareTo(BigDecimal.valueOf(1500)) == 1).count();
//计算年龄总和
int sumAge = userList.stream().collect(Collectors.summingInt(User::getAge));
//计算平均年龄
double aveAge = userList.stream().collect(Collectors.averagingDouble(User::getAge));
//获取IntSummaryStatistics对象
IntSummaryStatistics ageStatistics = userList.stream().collect(Collectors.summarizingInt(User::getAge));
//统计:最大值、最小值、总和、平均值、总数
System.out.println("最大年龄:" + ageStatistics.getMax());
System.out.println("最小年龄:" + ageStatistics.getMin());
System.out.println("年龄总和:" + ageStatistics.getSum());
System.out.println("平均年龄:" + ageStatistics.getAverage());
System.out.println("员工总数:" + ageStatistics.getCount());
//最高薪资
BigDecimal maxSalary = userList.stream().map(User::getSalary).max((x1, x2) -> x1.compareTo(x2)).get();
//最低薪资
BigDecimal minSalary = userList.stream().map(User::getSalary).min((x1, x2) -> x1.compareTo(x2)).get();
//薪资总和
BigDecimal sumSalary = userList.stream().map(User::getSalary).reduce(BigDecimal.ZERO, BigDecimal::add);
//平均薪资
BigDecimal avgSalary = userList.stream().map(User::getSalary).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(userList.size()), 2, BigDecimal.ROUND_HALF_UP);