java - 将方法作为参数传递并在 forEach 循环中使用

标签 java lambda java-8

我想在循环访问设备列表时调用删除函数。这些设备可以是两种类型之一 - 短信电话或电子邮件。这可以通过 Java 8 功能接口(interface)之一来实现吗?

// leaving out implementation details for simplicity
public class SmsPhone extends Device {
}

public class Email extends Device {
}

public class Device {
    private String contact;
    public String getContact() { return contact; }
    public void setContact(String contact) { this.contact = contact; }
}

public class MyService {

    public void updateEmail(String username, Collection<Email> allEmails, Collection<String> selectedEmails) {
        updateUserDevices(username, allEmails, selectedEmails);
    }

    public void updateSms(String username, Collection<SmsPhone> allPhones, Collection<String> selectedPhones) {
        updateUserDevices(username, allPhones, selectedPhones);
    }

    private void updateUserDevices(final String username, Collection<Device> devices, Collection<String> contacts) {

        // put all the device contact info in the list and then filter out the ones in the given devices collection.
        devices.stream()
            .map(d -> d.getContact())
            .filter(s -> !contacts.contains(s))
            .forEach(s -> /***Call either deleteEmail() or deleteSms()***/);
    }

    private void deleteEmail(String email) {}
    private void deleteSms(String sms) {}

}

最佳答案

尝试

private void updateUserDevices(final String username, Collection<Device> devices, Collection<String> contacts) {

    // put all the device contact info in the list and then filter out the ones in the given devices collection.
    devices.stream()
        .filter(d -> !contacts.contains(d.getContact()))
        .forEach(MyService::delete);
}

private void delete(Device d) {
    String contact = d.getContact();
    if (d.isEmail()) {
        deleteEmail(contact);
    } else {
        deleteSms(contact);
    }
}

private void deleteEmail(String email) {}
private void deleteSms(String sms) {}

关于java - 将方法作为参数传递并在 forEach 循环中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37993223/

相关文章:

javascript - 在 Java 中运行 Javascript : FilePermission denied

java - ConcurrentSkipListMap 如何使删除和添加调用原子化

java - 在奇数索引处反转队列中的数字

java - 有什么方法可以从静态方法中获取泛型 T 类对象(不调用构造函数)?

java - 为什么添加数据后无法刷新数据表?

java - 当 SAME 方法在 Java 中不返回值时,Lambda 会返回一个值

c# - 如何处理匿名类型 <T> 的强制转换委托(delegate),委托(delegate) T 以便在 IEnumerable<T> 的Where<T>() 方法中使用

c# - 如何解压表达式树并检查空值

java - 使用 Jackson 将瞬间序列化为毫秒?

java-8 - Java8 谓词与 try catch