17

I have this couple of functions and I would like to know if it is possible to pass the parameter deviceEvent.hasAlarm() to .map(this::sendSMS)

private void processAlarm (DeviceEvent deviceEvent)  {

        notificationsWithGuardians.stream()
                    .filter (notification -> notification.getLevels().contains(deviceEvent.getDeviceMessage().getLevel()))
                    .map(this::sendSMS)
                    .map(this::sendEmail);

    }

    private DeviceAlarmNotification sendSMS (DeviceAlarmNotification notification, DeviceEvent deviceEvent)  {

        if (deviceEvent.hasAlarm()) {       

        }

        return notification;

    }
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
La Carbonell
  • 1,976
  • 5
  • 22
  • 52

3 Answers3

56

Use a lambda instead of the method reference.

// ...
.map(n -> sendSMS(n, deviceEvent))
// ...
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
6

... I would like to know if it is possible to pass the parameter deviceEvent.hasAlarm() to this::sendSMS

No, is not possible. When using method reference you can pass only one argument (docs).

But from the code you provided there is no need for such thing. Why to check deviceEvent for every notification when it is not changing? Better way:

if(deviceEvent.hasAlarm()) {
  notificationsWithGuardians.stream().filter( ...
}

Anyway, if you really want, this can be a solution:

notificationsWithGuardians.stream()
                .filter (notification -> notification.getLevels().contains(deviceEvent.getDeviceMessage().getLevel()))
                .map(notification -> Pair.of(notification, deviceEvent))
                .peek(this::sendSMS)
                .forEach(this::sendEmail);

 private void sendSMS(Pair<DeviceAlarmNotification, DeviceEvent> pair)  { ... }
Adrian
  • 2,984
  • 15
  • 27
0

How about creating a Class or Member vaiable and assigning value to it and reusing in the reference method provided if reference method is in same class

dheeraj
  • 195
  • 2
  • 19