import java.util.*;
public class ComparatorExample {
public static void main(String[] args) {
// 创建一个包含自定义对象的列表
List<Employee> employees = Arrays.asList(
new Employee("John", 30, 5000),
new Employee("Jane", 25, 6000),
new Employee("Jim", 35, 4800)
);
// 使用Comparator对员工按年龄排序
employees.sort(Comparator.comparingInt(Employee::getAge));
// 打印排序后的结果
System.out.println("按年龄排序:");
employees.forEach(System.out::println);
// 使用Comparator对员工按工资降序排序
employees.sort(Comparator.comparingDouble(Employee::getSalary).reversed());
// 打印排序后的结果
System.out.println("按工资降序排序:");
employees.forEach(System.out::println);
}
}
class Employee {
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Employee{name='" + name + "', age=" + age + ", salary=" + salary + "}";
}
}
java.util.*,以便使用List、Arrays和Comparator等类。Employee对象的列表,每个Employee对象有姓名、年龄和工资属性。Comparator.comparingInt(Employee::getAge)对员工按年龄进行升序排序。Comparator.comparingDouble(Employee::getSalary).reversed()对员工按工资进行降序排序。forEach方法遍历并打印排序后的员工列表。这段代码展示了如何使用Comparator接口来对自定义对象进行排序。
上一篇:java读取文件内容
下一篇:java sm4加密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站