Java 8集合:带功能的过滤器不起作用

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>

Ser*_*tin 8

filter应该在Stream对象上调用方法.

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)

  • 查看错误,`findAll`返回一个`Iterable <DeviceEvent>`,它没有`stream()`方法.因此,您需要首先将iterable转换为流.请参阅/sf/ask/1675244301/ (5认同)