• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

java8的Stream的排序

work summary 来源:ziwencsdn 3次浏览

要是想使用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()));//打印

版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)