2

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>
  • findAll returns a Iterable<DeviceEvent>
Holger
  • 285,553
  • 42
  • 434
  • 765
Nuñito Calzada
  • 4,394
  • 47
  • 174
  • 301

1 Answers1

8

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
Valentin Michalak
  • 2,089
  • 1
  • 14
  • 27
Sergii Lagutin
  • 10,561
  • 1
  • 34
  • 43
  • 5
    Looking at the error, `findAll` returns an `Iterable`, which doesn't have a `stream()`, method. So you need to convert the iterable to a stream in the first place. See https://stackoverflow.com/questions/23932061/convert-iterable-to-stream-using-java-8-jdk – Alexis C. Jan 29 '18 at 14:39