package org.example;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
/**
* 学生序号
*/
private String id;
/**
* 学生姓名
*/
private String name;
/**
* 学生分数
*/
private double score;
/**
* 所学课程
*/
List<String> course;
/**
* 班级
*/
private String StudentClass;
public Student(String StudentClass,String id,String name, double score) {
this.StudentClass = StudentClass;
this.id = id;
this.name = name;
this.score = score;
}
}
stream流常用的过滤,排序,分组,转换。
package org.example;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Student> students = initData();
streamImpl(students);
// java7Impl(students);
}
public static void streamImpl(List<Student> students) {
// Stream流 按成绩来进行过滤
List<Student> filterStudent = students.stream()
.filter(student -> student.getScore() < 60).collect(Collectors.toList());
// Stream流 按成绩范围来进行过滤
List<Student> collect = students.stream().filter(student -> student.getScore() < 60 && student.getScore() > 20).collect(Collectors.toList());
// stream流 将对象进行转换
List<Map> collect = students.stream().map(student -> {
Map map = new HashMap();
map.put("序号",student.getId());
map.put("姓名", student.getName());
map.put("成绩", student.getScore());
return map;
}).collect(Collectors.toList());
// stream流 按成绩倒叙来进行排序
List<Student> collect = students.stream().sorted(Comparator.comparing(Student::getScore).reversed()).collect(Collectors.toList());
// stream流 按序号正序排序
List<Student> collect = students.stream().sorted(Comparator.comparing(Student::getId)).collect(Collectors.toList());
Map<String, List<Student>> collect1 = collect.stream().collect(Collectors.groupingBy(Student::getStudentClass));
// stream流 按班级分组并在每个班级内按序号倒叙排序
Map<String, List<Student>> collect =
students.stream().collect(Collectors.groupingBy(Student::getStudentClass, Collectors.collectingAndThen(Collectors.toList()
, list -> list.stream().sorted(Comparator.comparing(Student::getId).reversed()).collect(Collectors.toList()))));
// 利用stream进行分页处理
Integer pageSize = 2;//条数
Integer pageNo = 1;//页数
List<Student> collect = students.stream().skip((pageNo - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
}
public static List<Student> initData() {
List<Student> students = new ArrayList<>();
students.add(new Student("一班","1","张三", 60));
students.add(new Student("一班","2","李四", 80));
students.add(new Student("一班","3","王五", 50));
students.add(new Student("二班","1","赵六", 70));
students.add(new Student("二班","2","孙七", 80));
students.add(new Student("二班","3","孙七", 80));
students.add(new Student("三班","1","周八", 30));
students.add(new Student("三班","2","周八", 30));
return students;
}
}