gpt4 book ai didi

java - 如何仅从所需的类(流)获取数据?

转载 作者:行者123 更新时间:2023-12-02 16:04:51 25 4
gpt4 key购买 nike

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) {} .正如你在上面看到的,只有 WorkerManager可以有奖金,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com