首先,我们需要创建一个教师类Teacher:public class Teacher { private String name; private double salary; public Teacher(String name, double salary) { this.name = name; this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } @Override public String toString() { return "Teacher{" + "name='" + name + '\'' + ", salary=" + salary + '}'; }}
接下来,我们创建一个比较器类MyComparer,其中包含两个静态方法用于排序:import java.util.Comparator;public class MyComparer { public static int compareBySalory(Teacher t1, Teacher t2) { if (t1.getSalary() < t2.getSalary()) { return -1; } else if (t1.getSalary() > t2.getSalary()) { return 1; } else { return 0; } } public static int compareBySaloryDesc(Teacher t1, Teacher t2) { if (t1.getSalary() < t2.getSalary()) { return 1; } else if (t1.getSalary() > t2.getSalary()) { return -1; } else { return 0; } }}
使用匿名内部类进行排序的应用程序:import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class Main { public static void main(String[] args) { List<Teacher> teachers = new ArrayList<>(); teachers.add(new Teacher("张三", 5000)); teachers.add(new Teacher("李四", 8000)); teachers.add(new Teacher("王五", 6000)); Collections.sort(teachers, new Comparator<Teacher>() { @Override public int compare(Teacher t1, Teacher t2) { return MyComparer.compareBySalory(t1, t2); } }); for (Teacher teacher : teachers) { System.out.println(teacher); } }}
使用lambda表达式进行排序的应用程序:import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class Main { public static void main(String[] args) { List<Teacher> teachers = new ArrayList<>(); teachers.add(new Teacher("张三", 5000)); teachers.add(new Teacher("李四", 8000)); teachers.add(new Teacher("王五", 6000)); Collections.sort(teachers, (t1, t2) -> MyComparer.compareBySalory(t1, t2)); for (Teacher teacher : teachers) { System.out.println(teacher); } }}
使用方法引用进行排序的应用程序:import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class Main { public static void main(String[] args) { List<Teacher> teachers = new ArrayList<>(); teachers.add(new Teacher("张三", 5000)); teachers.add(new Teacher("李四", 8000)); teachers.add(new Teacher("王五", 6000)); Collections.sort(teachers, MyComparer::compareBySalory); for (Teacher teacher : teachers) { System.out.println(teacher); } }}
以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。 |