【发布时间】:2021-12-13 02:10:09
【问题描述】:
Employee类:
public abstract class Employee extends Person {
private final Manager manager;
private final BigDecimal salary;
protected Employee(String firstName, String surname, LocalDate birth_date, Manager _manager, BigDecimal _salary) {
super(firstName, surname, birth_date);
manager = _manager;
salary = _salary;
if (manager != null) {
manager.getSubordinates().add(this);
}
}
...
}
Worker类:
public class Worker extends Employee {
private final LocalDate employment_date;
private BigDecimal bonus;
public Worker(String firstName, String surname, LocalDate birth_date, Manager manager, BigDecimal salary,
LocalDate _employment_date, BigDecimal _bonus) {
super(firstName, surname, birth_date, manager, salary);
employment_date = _employment_date;
bonus = _bonus;
}
...
}
Manager类:
public final class Manager extends Worker {
List<Employee> subordinates = new ArrayList<Employee>();
public Manager(String firstName, String surname, LocalDate birth_date, Manager manager, BigDecimal salary,
LocalDate employment_date, BigDecimal bonus) {
super(firstName, surname, birth_date, manager, salary, employment_date, bonus);
}
...
}
Trainee类:
public class Trainee extends Employee {
private final LocalDate start_date;
private final short apprenticeship_length;
public Trainee(String firstName, String surname, LocalDate birth_date, Manager manager, BigDecimal salary,
LocalDate _start_date, short _apprenticeship_length) {
super(firstName, surname, birth_date, manager, salary);
manager.getSubordinates().add(this);
start_date = _start_date;
apprenticeship_length = _apprenticeship_length;
}
}
payrol类:
public final class PayrollEntry {
private final Employee _employee;
private final BigDecimal _salaryPlusBonus;
public PayrollEntry(Employee employee, BigDecimal salary, BigDecimal bonus) {
_employee = employee;
_salaryPlusBonus = salary.add(bonus);
}
}
我必须编写函数List<PayrollEntry> payroll(List<Employee> employees) {}。正如您在上面看到的,只有Worker 和Manager 可以有奖金,另一方面Trainee 没有,但它们都派生自Employee 类(顺便说一句,我无法更改类中的任何内容层次结构,因为这是我的作业,层次结构是由老师编写的)。我应该使用函数式编程技术来编写函数,这是我的尝试:
public static List<PayrollEntry> payroll(List<Employee> employees) {
return employees
.stream()
.map(employee -> new PayrollEntry(employee, employee.getSalary(), ((Worker) employee).getBonus()))
.collect(Collectors.toList());
}
我明白为什么它给了我ClassCastException,但我不知道有任何其他方法可以使用stream。我想我可以使用for-each 循环检查每次是否为Trainee,但我想知道是否有使用stream 的方法。
【问题讨论】:
-
你可以使用
filter -
@QBrute 如果可能的话,我必须得到
Salary和Bonus。如果我使用过滤器只检查Worker和Manager类,那么我将不会处理Trainee的实例。我必须检查给定的Employee是否有Bonus和Salary或只有Salary
标签: java class java-stream hierarchy