java8的Stream的排序

时间:2025-04-01 19:21:20

要是想使用sort功能,那么首先:

  1. 定义实体类:
public class Student implements Comparable<Student> {


    private int id;
    private String name;
    private int age;

    public Student(int id, String name, int age) {
         = id;
         = name;
         = age;
    }


    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }


    public void setId(int id) {
         = id;
    }

    public void setName(String name) {
         = name;
    }

    public void setAge(int age) {
         = age;
    }

    @Override
    public int compareTo(Student o) {
        return (());
    }

    @Override
    public boolean equals(final Object obj){
        if (null==obj){
            return false;
        }

        final Student std= (Student) obj;
        if (this==std){
            return true;
        }else {
            return ((())) && (==());
        }
    }

    @Override
    public int hashCode(){
        int hashno=7;
        hashno=13*hashno+(name==null?0:());
        return hashno;
    }
}
  1. 进行排序:

List<Student> studentList=(new Student(1,"ziwen1",10),new Student(2,"aiwen2",18),new Student(3,"biwen3",28));

List<Student> studentList1=().sorted().collect(());//自然序列

List<Student> studentList2=().sorted(()).collect(());//逆序

List<Student> studentList3=().sorted((Student::getAge)).collect(());//根据年龄自然顺序

List<Student> studentList4=().sorted((Student::getAge).reversed()).collect(());//根据年龄逆序

studentList4.forEach(student -> ("id is "+()+" ;name is "+()+";age is "+()));//打印