作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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
(顺便说一句,我无法更改类(class)层次结构中的任何内容,因为这是我的作业,而层次结构是由老师编写的)。我应该使用函数式编程技术来编写函数,这是我的尝试:
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
.
最佳答案
对于 map() 的内容应该有什么限制?
否则你可以有类似的东西:
.map(employee -> {
if (employee instanceof Worker) {
return new PayrollEntry()....
} else {
return new PayrollEntry()....
}
})
关于java - 如何仅从所需的类(流)获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69744510/
我是一名优秀的程序员,十分优秀!