为什么我不能将谓词应用于 java 流过滤器?
why cannot I apply a predicate to java stream filter?
我有这个代码:
@Override
public List<Device> getAvailableDevices(Predicate<Device> filter) {
return deviceRepository.getDevices()
.stream()
.filter(filter)
.collect(Collectors.toList());
}
我得到这个错误:
Error:(55, 25) java: incompatible types: com.google.common.base.Predicate<com.m.automation.common.mobile.services.devices.dataModel.Device> cannot be converted to java.util.function.Predicate<? super com.m.automation.common.mobile.services.devices.dataModel.Device>
我该如何解决这个问题?
您使用的是 Guava 谓词,而不是 java.util.function.Predicate
。这由源文件中的 import
语句决定。
如果您可以更改此代码及其调用方,请更改此 getAvailableDevices()
方法的类型以接受 java.util.function.Predicate
。只需更改您的导入指令即可完成此操作,但它可能会影响其他代码;如果您真的想在其他地方继续使用 Guava 谓词,您可以使用完全限定名称 java.util.function.Predicate
.
来针对此方法进行更改
如果您无法更改此方法签名,请通过将 filter(filter)
替换为 filter(filter::apply)
来调整您拥有的过滤器以适应标准 Predicate
。
我有这个代码:
@Override
public List<Device> getAvailableDevices(Predicate<Device> filter) {
return deviceRepository.getDevices()
.stream()
.filter(filter)
.collect(Collectors.toList());
}
我得到这个错误:
Error:(55, 25) java: incompatible types: com.google.common.base.Predicate<com.m.automation.common.mobile.services.devices.dataModel.Device> cannot be converted to java.util.function.Predicate<? super com.m.automation.common.mobile.services.devices.dataModel.Device>
我该如何解决这个问题?
您使用的是 Guava 谓词,而不是 java.util.function.Predicate
。这由源文件中的 import
语句决定。
如果您可以更改此代码及其调用方,请更改此 getAvailableDevices()
方法的类型以接受 java.util.function.Predicate
。只需更改您的导入指令即可完成此操作,但它可能会影响其他代码;如果您真的想在其他地方继续使用 Guava 谓词,您可以使用完全限定名称 java.util.function.Predicate
.
如果您无法更改此方法签名,请通过将 filter(filter)
替换为 filter(filter::apply)
来调整您拥有的过滤器以适应标准 Predicate
。