我想在循环访问设备列表时调用删除函数。这些设备可以是两种类型之一 - 短信电话或电子邮件。这可以通过 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/