[英]How do we iterate through muliple list and call a setter method using java streams
I have 2 lists.我有 2 个列表。
List<Email> emailList emailList = getEmails();
List<FileData> fileList = getFileList();
public class Email {
private String email;
private String name;
private String type;
private Set<Permissions>;
//getter and setter
}
public class Permissions {
private String permissionType;
private String level;
//getter and setter
}
public class FileData {
private String email;
private String type;
//getter and setter
}
I need to iterate through the list match the email from both list and call setPermissionType() method and if there is no match with the Email it needs to throw NotFoundException.我需要遍历列表匹配来自列表的电子邮件并调用 setPermissionType() 方法,如果与电子邮件不匹配,则需要抛出 NotFoundException。 How can we do this with Java streams?
我们如何使用 Java 流来做到这一点?
The logic I have at the moment is.我目前的逻辑是。
for (final FileData fileData: fileList ) {
Email email= emailDao.findByEmail(fileData.getEmail()); //throws NotFoundException
final Set<Permissions> permissions = email.getPermissions();
permissions.removeIf(p -> p.getPermissionType() == fileData.getType());
email.setPermissions(permissions);
}
In the above logic I'm making DB calls in a for loop.在上面的逻辑中,我在 for 循环中进行数据库调用。 I need to avoid that by using IN clause.
我需要通过使用 IN 子句来避免这种情况。
List<String> emailStringList = fileList.stream()
.map(file -> Objects.toString(file.getEmail()))
.collect(Collectors.toList());
List<Email> emailList= emailDao.findByEmailIn(emailStringList);
First of all, I would suggest to remove emailDao.findByEmail() inside a loop, this costs you a huge cost and technical debt首先,我建议在循环中删除 emailDao.findByEmail() ,这会花费您巨大的成本和技术债务
First of all, create a list of emails首先,创建一个电子邮件列表
List<String> emailIds = fileList.stream().map(fileData->FileData::getEmail).collect(Collectors.toList());
Create a new method findByEmails(List emails) to find by multiple emails.创建一个新方法 findByEmails(List emails) 以通过多封电子邮件进行查找。
List<Email> emails = emailDao.findByEmails(emailIds);
I think, Something like this would work我认为,这样的事情会奏效
emails.forEach(email-> email.setPermissions(email.getPermissions().stream().fiter(permission -> !permission.getType().equals(fileList.stream().filter(file-> file.getEmail().equals(email.getEmail()).findFirst().orElse(new Permission())).getType()))))
Also, I think this will eliminate the NotFoundException as we're iterating only on the already existing emails.此外,我认为这将消除 NotFoundException,因为我们只对现有的电子邮件进行迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.