Please anyone help me to do this in Java8 streamAPI,
for(ContactDto contact : contactList){
for(ContactContactTypeDto contactType : contact.getContactTypes()){
if(PRIMARY_CONTACT.equals(contactType.getIdContactTypeCode())){
StringBuilder contactNameSB = new StringBuilder(contact.getFirstName());
contactNameSB.append(" ");
if(null!=contact.getMiddleName() && !contact.getMiddleName().isEmpty()){
contactNameSB.append(contact.getMiddleName());
contactNameSB.append(" ");
}
contactNameSB.append(contact.getLastName());
contactName = contactNameSB.toString();
contactEmail = contact.getEmailAddress();
}
}
}
I tried but I am reach only upto
contactList.stream()
.filter(contact -> contact.getContactTypes()
.stream()
.anyMatch(contactType -> PRIMARY_CONTACT.equals(contactType.getIdContactTypeCode())));
When code with java 8 streams get convoluted it is beneficial to create some additional types and methods. E.g.
A method to create a full name from it's parts (you don't need StringBuilder the compiler will use one in this case):
String createFullName(ContactDto contact) {
String contactName = contact.getFirstName() + " ";
if (null != contact.getMiddleName() && !contact.getMiddleName().isEmpty()) {
contactName += contact.getMiddleName() + " ";
}
return contactName + contact.getLastName();
}
A class to hold the result, basically a pair of name and email (add constructor, getters etc):
class Contact {
private String name;
private String email;
}
And now the code becomes much simpler:
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()));
Extra code after what you have done is findFirst which will returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.
The last map will be applied on the resulting Optional<ContactDTO> if it's not empty to create a Contact or else return an empty Optional<Contact>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With