带有参数的 Java 8 流映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44848086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:45:17  来源:igfitidea点击:

Java 8 streams maps with parameters

javalambdafunctional-programmingjava-8java-stream

提问by La Carbonell

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)

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

    }

采纳答案by Andy Turner

Use a lambda instead of the method reference.

使用 lambda 而不是方法引用。

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

回答by Adrian

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

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

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

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

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

但是从您提供的代码来看,不需要这样的东西。为什么在deviceEvent没有变化的情况下检查每个通知?更好的方法:

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)  { ... }

回答by dheeraj

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

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