自定义学生类代码:
import java.util.Objects; public class Student { private String name;//姓名 private int score;//成绩 @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", score=" + score + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return score == student.score && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(name, score); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public Student(String name, int score) { this.name = name; this.score = score; } }
测试类代码
import java.util.Arrays; public class Test06 { public static void main(String[] args) { //1. 定义一个学生类,有两个属性。姓名,考试成绩 //2. 在测试类中定义一个学生数组,存储学生信息。 //3. 使用Lambda省略格式写法对学生数组按照考试成绩由高到低进行排序。 Student[] array = {//学生对象数组 new Student("宋远桥", 99), new Student("张翠山", 100), new Student("张无忌", 34), new Student("俞岱岩", 98), }; //匿名内部类 /* Arrays.sort(array, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o2.getScore() - o1.getScore(); } });*/ //lambda表达式简写格式 Arrays.sort(array,(a,b)->b.getScore()-a.getScore()); for (Student stu : array) { System.out.println(stu); } } }
控制台打印的效果图: