用java实现以下代码: 定义Staff类(职工),添加如下属性(name, address, age, sex, salary, dateHired),类型自定,其中salary为工资,dateHired为雇佣日期(java.util.Date类型)。生成相应的setter/getter方法。编写NameComparator,AgeComparator和ComplexComparator比较器。其中ComplexComparator为复合比较器,选用工资和雇佣日期进行升序排序。比较器中需要使用Lambda表达式来完成
时间: 2024-02-11 16:04:02 浏览: 118
以下是用Java实现的代码:
```
import java.util.*;
public class Staff {
private String name;
private String address;
private int age;
private String sex;
private double salary;
private Date dateHired;
public Staff(String name, String address, int age, String sex, double salary, Date dateHired) {
this.name = name;
this.address = address;
this.age = age;
this.sex = sex;
this.salary = salary;
this.dateHired = dateHired;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Date getDateHired() {
return dateHired;
}
public void setDateHired(Date dateHired) {
this.dateHired = dateHired;
}
}
class NameComparator implements Comparator<Staff> {
public int compare(Staff a, Staff b) {
return a.getName().compareTo(b.getName());
}
}
class AgeComparator implements Comparator<Staff> {
public int compare(Staff a, Staff b) {
return a.getAge() - b.getAge();
}
}
class ComplexComparator implements Comparator<Staff> {
public int compare(Staff a, Staff b) {
if (a.getSalary() != b.getSalary()) {
return Double.compare(a.getSalary(), b.getSalary());
} else {
return a.getDateHired().compareTo(b.getDateHired());
}
}
}
class Main {
public static void main(String[] args) {
List<Staff> staffList = new ArrayList<>();
staffList.add(new Staff("Alice", "123 Main St", 25, "F", 50000, new Date(2021, 1, 1)));
staffList.add(new Staff("Bob", "456 Second St", 30, "M", 60000, new Date(2020, 1, 1)));
staffList.add(new Staff("Charlie", "789 Third St", 35, "M", 70000, new Date(2019, 1, 1)));
// Sort by name using NameComparator
Collections.sort(staffList, new NameComparator());
System.out.println("Sorted by name:");
for (Staff staff : staffList) {
System.out.println(staff.getName());
}
// Sort by age using AgeComparator
Collections.sort(staffList, new AgeComparator());
System.out.println("Sorted by age:");
for (Staff staff : staffList) {
System.out.println(staff.getAge());
}
// Sort by salary and date hired using ComplexComparator
Collections.sort(staffList, new ComplexComparator());
System.out.println("Sorted by salary and date hired:");
for (Staff staff : staffList) {
System.out.println(staff.getSalary() + ", " + staff.getDateHired());
}
}
}
```
阅读全文