-1

I need to check if the Id variable of a class is null or not. If it is null I must insert it in one list and if it is not null I must insert it in another list. I'm doing it this way:

I didn't want two streams, I would like to do only one and Strem and filter, can you help me?

Emails with null ids will persist in the database.

List<Email> emails = payment.getUser().getEmails();

if (!emails.isEmpty()){
    List<Email> create = emails.stream().filter(email -> email.getId() == null).collect(Collectors.toList());
    List<Email> existingEmails = emails.stream().filter(email -> email.getId() != null).collect(Collectors.toList());
}
azro
  • 53,056
  • 7
  • 34
  • 70

1 Answers1

6

Use partitioningBy

List<Email> emails = payment.getUser().getEmails();
Map<Boolean, List<Email>> result = emails.stream().collect(Collectors.partitioningBy(email -> email.getId() == null));

List<Email> create = result.get(true);
List<Email> existingEmails = result.get(false);
b.GHILAS
  • 2,273
  • 1
  • 8
  • 16