Java Stream的使用
过滤
List<Student> studentList = new ArrayList<>();
Student student1 = new Student("张三", 23, 0L, 175.5, 65);
Student student2 = new Student("李四", 24, 0L, 180, 70);
Student student3 = new Student("王五", 25, 0L, 167, 60);
Student student4 = new Student("翠花", 18, 1L, 165, 55);
Student student5 = new Student("如花", 19, 1L, 158, 60);
Student student6 = new Student("花花", 20, 1L, 172, 58);
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
studentList.add(student4);
studentList.add(student5);
studentList.add(student6);
//过滤
//男学生集合
List<Student> maleStudents = studentList.stream().filter(student -> student.getSex().equals(0L)).collect(Collectors.toList());
//女学生集合
List<Student> femaleStudents = studentList.stream().filter(student -> student.getSex().equals(1L)).collect(Collectors.toList());
System.out.println("maleStudents:"+maleStudents);
System.out.println("femaleStudents:"+femaleStudents);
执行结果:
分组
//分组
//根据性别分组
Map<Long, List<Student>> groupBySexMap=studentList.stream().collect(Collectors.groupingBy(Student::getSex));
System.out.println(groupBySexMap);
结果:
统计
//统计
//获取学生年龄总和
int sum = studentList.stream().mapToInt(Student::getAge).sum();
System.out.println("年龄总和:"+sum);
//体重总和
double sum1 = studentList.stream().mapToDouble(Student::getWeight).sum();
System.out.println("体重总和:"+sum1);
//BigDecimal求和用list.stream().map(Money::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add);
结果:
排序
//根据年龄升序排序
List<Student> sortAgeList = studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
//根据升高降序排序
List<Student> sortHeightList = studentList.stream().sorted(Comparator.comparing(Student::getHeight).reversed()).collect(Collectors.toList());
//先跟据升高升序排序,身高相同时按照体重降序
Student student7 = new Student("翠花2", 18, 1L, 165, 50);
studentList.add(student7);
List<Student> sortList = studentList.stream().sorted(Comparator.comparing(Student::getHeight).thenComparing(Student::getWeight,Comparator.reverseOrder())).collect(Collectors.toList());
System.out.println("sortAgeList:"+sortAgeList);
System.out.println("sortHeightList:"+sortHeightList);
System.out.println("sortList:"+sortList);;
结果:
转map
//key=name value=student
Map<String, Student> studentMap = studentList.stream().collect(Collectors.toMap(Student::getName, student -> student));
结果:
收集某一字段
//收集某一字段
List<Integer> ageList = studentList.stream().map(Student::getAge).collect(Collectors.toList());
System.out.println(ageList);
结果:
去重
//学生的重量分布,去除相同的重量
List<Double> distinctList = studentList.stream().map(Student::getWeight).distinct().collect(Collectors.toList());
System.out.println(distinctList);
结果:
简单例举了流的常用几种方式,通过复合使用可以完成相对复杂的业务情况。