Java 8中带参数的流映射

17

我有这几个函数,想知道是否可以将参数deviceEvent.hasAlarm()传递给.map(this::sendSMS)

Translated: 我有这几个函数,想知道是否可以将参数deviceEvent.hasAlarm()传递给.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;

    }
3个回答

56

使用Lambda表达式代替方法引用。

// ...
.map(n -> sendSMS(n, deviceEvent))
// ...

6

我想知道是否可以将参数deviceEvent.hasAlarm() 传递给 this::sendSMS

不行。使用方法引用时,只能传递一个参数 (文档)。

但是从您提供的代码中,没有必要这样做。当 deviceEvent 不会改变时,为什么要在每个通知中都检查它? 更好的方式:

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

无论如何,如果你真的想要,这可能是一个解决方案:
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)  { ... }

0
如何创建一个类或成员变量,并为其赋值,在提供的引用方法中重复使用,如果引用方法在同一类中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接