Nuñ*_*ada 2 java collections functional-programming java-8 java-stream
我有这段代码,从具有某些条件的DeviceEvents列表中提取
List<DeviceEvent> deviceEvents = new ArrayList<>();
deviceEventService
.findAll(loggedInUser())
.filter(this::isAlarmMessage)
.iterator()
.forEachRemaining(deviceEvents::add);
private boolean isAlarmMessage (DeviceEvent deviceEvent) {
return AlarmLevelEnum.HIGH == deviceEvent.getDeviceMessage().getLevel();
}
Run Code Online (Sandbox Code Playgroud)
但我得到了这个编译错误:
The method filter(this::isAlarmMessage) is undefined for the type
Iterable<DeviceEvent>
Run Code Online (Sandbox Code Playgroud)
findAll 返回一个 Iterable<DeviceEvent> List<DeviceEvent> deviceEvents = deviceEventService
.findAll(loggedInUser()).stream()
.filter(this::isAlarmMessage)
.collect(toList());
Run Code Online (Sandbox Code Playgroud)
此外,您不应该创建空ArrayList以收集结果.使用Stream.collect适当的收集器.
如果findAll返回Iterable,首先需要将其转换为流.
StreamSupport.stream(
deviceEventService.findAll(loggedInUser()).spliterator(), false)
.stream() // and so on
Run Code Online (Sandbox Code Playgroud)