简体   繁体   中英

How do we iterate through muliple list and call a setter method using java streams

I have 2 lists.

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. How can we do this with Java streams?

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. I need to avoid that by using IN clause.

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

  1. First of all, create a list of emails

    List<String> emailIds = fileList.stream().map(fileData->FileData::getEmail).collect(Collectors.toList());

  2. Create a new method findByEmails(List emails) to find by multiple emails.

    List<Email> emails = emailDao.findByEmails(emailIds);

  3. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM