【问题标题】:How to get data only from desired classes (stream)?如何仅从所需的类(流)中获取数据?
【发布时间】: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&lt;PayrollEntry&gt; payroll(List&lt;Employee&gt; employees) {}。正如您在上面看到的,只有WorkerManager 可以有奖金,另一方面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 如果可能的话,我必须得到SalaryBonus。如果我使用过滤器只检查WorkerManager 类,那么我将不会处理Trainee 的实例。我必须检查给定的Employee 是否有BonusSalary 或只有Salary

标签: java class java-stream hierarchy


【解决方案1】:

对 map() 的内容有什么限制吗?

否则你可以有类似的东西:

.map(employee -> {
    if (employee instanceof Worker) {
        return new PayrollEntry()....
    } else {
        return new PayrollEntry()....
    }
})

【讨论】:

    【解决方案2】:

    我会为这些情况创建一个静态构造函数。 (类似于PayrollEntry.forEmployee(Employee))由于您不应该更改原始类,因此您可以将方法放在其他地方。

    private static PayrollEntry newPayrollEntry(Employee employee) {
        BigDecimal bonus = BigDecimal.ZERO;        
        if (employee instanceof Worker) {
            bonus = ((Worker) employee).getBonus();
        }
        return new PayrollEntry(employee, employee.getSalary(), bonus);
    }
    
    public static List<PayrollEntry> payroll(List<Employee> employees) {
        return employees
                .stream()
                .map(Main::newPayrollEntry)
                .collect(Collectors.toList());
    }
    

    您也可以将相同的代码放在大括号中,但将代码移动到静态方法中更容易阅读。

    stream.map(employee -> {
        // Long code
        return payroll;
    })
    

    【讨论】:

      【解决方案3】:

      我不确定它是否符合你老师给你的任务定义,但你可以扩展你的map流操作如下:

      public static List<PayrollEntry> payroll(List<Employee> employees) {
              return employees
                      .stream()
                      .map(employee -> {
                          // if statements to check type of employee
                          // set some variables for the various fields
                          return new PayroleEntry(...);
                      })
                      .collect(Collectors.toList());
      }
      

      【讨论】:

        【解决方案4】:

        您可以在强制转换之前使用三元运算符并检查employee 是否是Worker 类的实例。如果是则通过奖金否则BigDecimal.ZERO

        employees.stream()
                 .map(employee -> new PayrollEntry(employee, employee.getSalary(),
                       employee instanceof Worker ? ((Worker) employee).getBonus() : BigDecimal.ZERO))
                 .collect(Collectors.toList());
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-12
          • 2018-03-20
          • 1970-01-01
          • 1970-01-01
          • 2022-07-20
          • 2017-04-27
          • 2011-11-04
          • 1970-01-01
          相关资源
          最近更新 更多