java8的Stream的排序

要是想使用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) {
        this.id = id;
        this.name = name;
        this.age = age;
    }


    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }


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

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

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

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

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

        final Student std= (Student) obj;
        if (this==std){
            return true;
        }else {
            return (this.name.equals(std.getName())) && (this.age==std.getAge());
        }
    }

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

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

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

List<Student> studentList2=studentList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());//逆序

List<Student> studentList3=studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());//根据年龄自然顺序

List<Student> studentList4=studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());//根据年龄逆序

studentList4.forEach(student -> System.out.println("id is "+student.getId()+" ;name is "+student.getName()+";age is "+student.getAge()));//打印
    原文作者:ziwencsdn
    原文地址: https://blog.csdn.net/ziwenCSDN/article/details/78625426
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞