When the code with java 8 threads is confused, it is useful to create some additional types and methods. For instance.
The method of creating the full name from its parts (you do not need it StringBuilder, in this case the compiler will use one):
String createFullName(ContactDto contact) {
String contactName = contact.getFirstName() + " ";
if (null != contact.getMiddleName() && !contact.getMiddleName().isEmpty()) {
contactName += contact.getMiddleName() + " ";
}
return contactName + contact.getLastName();
}
A class for storing the result, basically a couple of names and email (add constructor, getters, etc.):
class Contact {
private String name;
private String email;
}
And now the code is much easier:
Optional<Contact> contact = contactList.stream()
.filter(c -> c.getContactTypes()
.stream()
.map(ContactContactTypeDto::getIdContactTypeCode)
.anyMatch(PRIMARY_CONTACT::equals))
.findFirst()
.map(c -> new Contact(createFullName(c), c.getEmailAddress()));
, , findFirst, Optional, , , .
map Optional<ContactDTO>, , Contact Optional<Contact>.