使用.collect(toList())时,推理变量T具有不兼容的边界

时间:2015-10-16 20:00:06

标签: java java-8 java-stream collectors

任务是:

  

修改名称以字母表后半部分字母开头的所有工人的奖金。

class Worker that extends Employee
{
    public Worker(String name, int yOfEmp, int salary, Manager boss){
        super(name, yOfEmp, salary,boss);
        boss.addEmployee(this);
    }

    public float getBonus(Employee emp){
        Random rand = new Random();
        float proc = rand.nextFloat();
        return emp.getSalary() * proc;
    }
    public float setBonus(Employee e, float proc){
        float newProc = proc;
        return e.getSalary() * proc;
    }

    @Override
    public String toString() {
        return super.toString();
    }
}
class RegWorker extends Worker
{
}
class Main
{
  public static void main(String[] str) {
    Manager bill = new Manager("Bill", 2010, 2549, null);
    Manager steven = new Manager("Steven", 2011, 2100, bill);
    Trainer jerry = new Trainer("Jerry", 2014, 800, steven);
    RegWorker john = new RegWorker("John", 2010, 1000, bill);
    RegWorker kate = new RegWorker("Kate", 2011, 1000, bill);
    RegWorker sam = new RegWorker("Sam", 2013, 1200, steven);

    final List<Worker> workers = Arrays.asList(jerry, john, kate, sam);

    System.out.println("Modify bonuses for all regular workers:");
    RegWorker reg = null;

    List<RegWorker> regWorkers = workers
                .stream()
                .filter(w -> w.getClass() == reg.getClass())
                .filter(w -> w.getName().charAt(0) < 'O')
                .map(w -> w.setBonus(w, w.getBonus(w)+3))
                .collect(toList());
    }

我有这个 error

  

原因:推理变量T具有不兼容的界限
  平等约束:RegWorker
  下限:浮动

1 个答案:

答案 0 :(得分:3)

当你执行map时,用mapper函数返回值替换流对象,返回值是setBonus的返回值,即float。因此,在map步骤之后,您没有Stream<RegWorker>,而是Stream<Float>应该收集到List<Float>

您似乎想要使用peek而不是map。此外,您需要将流元素投射到RegWorker类,原始流为Stream<Worker>。最后请注意,您的代码还有另一个问题会出现在运行时:reg.getClass()会抛出NullPointerException,因为reg为空。可能你只需要.filter(w -> w instanceof RegWorker)

List<RegWorker> regWorkers = workers
            .stream()
            .filter(w -> w instanceof RegWorker)
            .filter(w -> w.getName().charAt(0) < 'O')
            .map(w -> (RegWorker)w)
            .peek(w -> w.setBonus(w, w.getBonus(w)+3))
            .collect(toList());