Nuñito Calzada
Nuñito Calzada

Reputation: 2106

Java 8 collections: filter with function don't work

I have this piece of code, to extract from a List of DeviceEvents the ones with some condition

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();
    }

but I got this compilation error:

The method filter(this::isAlarmMessage) is undefined for the type 
 Iterable<DeviceEvent>

Upvotes: 2

Views: 279

Answers (1)

Sergii Lagutin
Sergii Lagutin

Reputation: 10671

filter method should be called on Stream object.

List<DeviceEvent> deviceEvents = deviceEventService
        .findAll(loggedInUser()).stream()
        .filter(this::isAlarmMessage)   
        .collect(toList());

Also you should not create empty ArrayList to collect results. Use Stream.collect with appropriate collector.

If findAll returns Iterable, firstly you need convert it to stream.

StreamSupport.stream(
    deviceEventService.findAll(loggedInUser()).spliterator(), false)
        .stream() // and so on

Upvotes: 8

Related Questions