Collectors.summingInt中减法操作报错:目标类型需为函数式接口
解决Collectors.summingInt中方法引用相减的报错问题
嘿,这个问题我之前也踩过坑!你现在的写法是直接把两个方法引用用减号连起来,Java根本没法识别这种操作,所以才会抛出“the target type of this expression must be a functional interface”的错误。
错误原因
MonitoredData::getEndTimeSeconds 和 MonitoredData::getStartTimeSeconds 本身是方法引用,属于函数式接口的实例,但Java并没有定义函数式接口实例之间的算术运算规则。你直接把它们用-连起来,编译器不知道该把这个表达式转换成什么类型的函数式接口,自然就报错了。
正确写法
你需要用Lambda表达式显式地对每个MonitoredData对象执行减法操作,这样编译器就能明确这是一个返回int值的函数式接口实现:
Map<String, Integer> hm = listData.stream() .collect(Collectors.groupingBy( MonitoredData::getActivity, Collectors.summingInt(data -> data.getEndTimeSeconds() - data.getStartTimeSeconds()) ));
为什么这样可行?
Lambda表达式 data -> data.getEndTimeSeconds() - data.getStartTimeSeconds() 会接收一个MonitoredData对象作为输入,调用它的两个时间方法并计算差值,最终返回一个int结果——这完全符合Collectors.summingInt()需要的ToIntFunction<MonitoredData>函数式接口的要求,编译器能清晰识别这个表达式的目标类型,自然就不会报错了。
内容的提问来源于stack exchange,提问作者sylar12
相关产品推荐
相关产品推荐

