【问题标题】:Java 8 streams maps with parametersJava 8 带参数的流映射
【发布时间】:2017-12-04 12:14:06
【问题描述】:

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

    }

【问题讨论】:

    标签: java lambda functional-programming java-8 java-stream


    【解决方案1】:

    使用 lambda 代替方法引用。

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

    【讨论】:

      【解决方案2】:

      ...我想知道是否可以将参数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)  { ... }
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-27
          • 2015-02-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-29
          相关资源
          最近更新 更多