1.首先创建需要的学生类集合
List<Student> studentList = new ArrayList<>();
studentList.add(new Student().setSex("男").setName("小马").setGrade("1班").setAge(12).setCard(2));
studentList.add(new Student().setSex("男").setName("小李").setGrade("2班").setAge(13).setCard(1));
studentList.add(new Student().setSex("女").setName("小红").setGrade("1班").setAge(8).setCard(3));
studentList.add(new Student().setSex("男").setName("小明").setGrade("2班").setAge(5).setCard(3));
studentList.add(new Student().setSex("女").setName("小丽").setGrade("2班").setAge(14).setCard(5));
studentList.add(new Student().setSex("女").setName("小田").setGrade("1班").setAge(14).setCard(6));
studentList.add(new Student().setSex("男").setName("小刘").setGrade("2班").setAge(14).setCard(4));
studentList.add(new Student().setSex("女").setName("小王").setGrade("1班").setAge(2).setCard(1));
studentList.add(new Student().setSex("女").setName("小张").setGrade("1班").setAge(14).setCard(2));
studentList.add(new Student().setSex("男").setName("小张").setGrade("2班").setAge(16).setCard(7));
2 .使用filter进行过滤 一共10个学生 筛选性别为男的学生, 即为只要性别为男的学生信息
List<Student> example1 = studentList.stream().filter(student -> "男".equals(student.getSex())).collect(Collectors.toList());
输出结果:
3.只获取所有的学生名字作为一个集合 加入distinct()可实现去重
List<String> example2 = studentList.stream().map(Student::getName).collect(Collectors.toList());
4.根据年龄进行排序 默认升序排序
List<Student> example3 = studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
输出结果:
5.根据年龄降序排序
List<Student> example4 = studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
输出结果:
6.排序 如果年龄相同,按照card进行降序排序
List<Student> example5 = studentList.stream().sorted(Comparator.comparing(Student::getAge, Comparator.naturalOrder()).thenComparing(Student::getCard, Comparator.reverseOrder())).collect(Collectors.toList());
输出结果:
7.获取学生年龄总和
long example6 = studentList.stream().collect(Collectors.summarizingInt(Student::getAge)).getSum();
8.获取学生年龄平均值
Double example7 = studentList.stream().collect(Collectors.summarizingInt(Student::getAge)).getAverage();
9.根据年龄进行分组
Map<Integer, List<Student>> example8 = studentList.stream().collect(Collectors.groupingBy(Student::getAge));
输出结果:
10.多级分组 ,先通过年龄再通过班级
Map<Integer, Map<String, List<Student>>> example9 = studentList.stream().collect(Collectors.groupingBy(Student::getAge, Collectors.groupingBy(Student::getGrade)));
11.根据班级进行分组,只要学生的年龄信息
Map<String, Set<Integer>> example10 = studentList.stream().collect(Collectors.groupingBy(Student::getGrade, Collectors.mapping(Student::getAge, Collectors.toSet())));
12.使用流进行分页操作
studentList.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
13 使用流获取重复的数据
List<Student> collect = studentList.stream().collect(Collectors.toMap(Function.identity(), s -> 1, Integer::sum))
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());