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

时间:2016-06-23 13:35:10

标签: java lambda java-8

我想在循环浏览设备列表时调用删除功能。这些设备可以是两种类型之一 - SmsPhone或Email。这可以通过Java 8 FunctionalInterfaces之一来实现吗?

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

}

2 个答案:

答案 0 :(得分:0)

尝试

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

答案 1 :(得分:0)

你应该使用抽象的Device方法使delete成为一个抽象类:

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

通过这种方式,您可以在任何delete上调用Device,而不知道其类型,Device的每个子类都可以按照自己的方式实现delete