首先初始化一个集合,用于我们下方的操作
Student stu1 = new Student(1, "dugt", 20);
Student stu2 = new Student(1, "lym", 10);
Student stu3 = new Student(3, "zs", 18);
Student stu4 = new Student(4, "ls", 18);
Student stu5 = new Student(4, "ww", null);
List<Student> list = Arrays.asList(stu1, stu2, stu3, stu4, stu5);
averagingInt ... averagingDouble 平均值
// 求平均年龄
Double aDouble = list.stream().filter(item -> item.getAge() != null).collect(Collectors.averagingDouble(Student::getAge)); // 这种方式把年龄为null的剔除掉
Double averageAge = list.stream().collect(Collectors.averagingInt(item -> item.getAge() == null ? 0 : item.getAge()));
count 求个数
// 求年龄为18的人数
long ageIs18 = list.stream().filter(item -> item.getAge() != null).filter(item -> item.getAge().compareTo(18) == 0).count();
groupingBy 分组
// 根据id分组
Map<Integer, List<Student>> map = list.stream().collect(Collectors.groupingBy(Student::getId));
groupingByConcurrent 保证线程安全分组
// 线程安全分组
ConcurrentMap<Integer, List<Student>> concurrentMap = list.stream().collect(Collectors.groupingByConcurrent(Student::getId));
map 根据某字段分组
//根据学生姓名集合
List<String> nameList = list.stream().map(Student::getName).collect(Collectors.toList());
根据id去重
// 根据id去重
List<Student> collect = new ArrayList<>(list.stream().collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getId)))));
max min 最大值最小值
// 求出年龄最大的同学
Student maxAgeStu = list.stream().filter(item -> item.getAge() != null).max(Comparator.comparing(Student::getAge)).get();