将员工先按工资再按年龄升序排序,java
时间: 2024-03-04 13:49:22 浏览: 63
可以使用Java中的Comparator接口和Collections.sort()方法来实现员工先按工资再按年龄升序排序,以下是示例代码:
首先,定义一个Employee类,包含工资和年龄两个属性:
```
public class Employee {
private double salary;
private int age;
public Employee(double salary, int age) {
this.salary = salary;
this.age = age;
}
public double getSalary() {
return salary;
}
public int getAge() {
return age;
}
}
```
然后,定义一个EmployeeComparator类实现Comparator接口,实现compare方法:
```
import java.util.Comparator;
public class EmployeeComparator implements Comparator<Employee> {
@Override
public int compare(Employee e1, Employee e2) {
// 先按工资升序排序
if (e1.getSalary() < e2.getSalary()) {
return -1;
} else if (e1.getSalary() > e2.getSalary()) {
return 1;
} else {
// 如果工资相同再按年龄升序排序
if (e1.getAge() < e2.getAge()) {
return -1;
} else if (e1.getAge() > e2.getAge()) {
return 1;
} else {
return 0;
}
}
}
}
```
最后,在主程序中创建一个Employee列表,使用Collections.sort()方法和EmployeeComparator进行排序:
```
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(6000, 30));
employees.add(new Employee(5000, 25));
employees.add(new Employee(4000, 35));
employees.add(new Employee(5000, 30));
Collections.sort(employees, new EmployeeComparator());
for (Employee e : employees) {
System.out.println("Salary: " + e.getSalary() + ", Age: " + e.getAge());
}
}
}
```
运行结果为:
```
Salary: 4000.0, Age: 35
Salary: 5000.0, Age: 25
Salary: 5000.0, Age: 30
Salary: 6000.0, Age: 30
```
阅读全文