带有参数的 Java 8 流映射

新手上路,请多包涵

我有这几个函数,我想知道是否可以将参数 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;

    }

原文由 La Carbonell 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 406
2 个回答

使用 lambda 而不是方法引用。

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

原文由 Andy Turner 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

不,不可能。使用方法引用时,您只能传递一个参数 ( docs )。

但是从您提供的代码来看,不需要这样的东西。为什么要检查 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)  { ... }

原文由 Adrian 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏