Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String append in java

I am constructing single string value based on some other string details, which is as below.
But don’t wants to add if any of DTO value is null or empty. How can I add it in java.

String dummyVal = new StringBuffer ("<b> test Id </b> ").append(someDTO.getId()).append(", ")
.append("<b> Type: </b> ").append(someDTO.getType()).append(", ")
.append("<b> Date: </b> ").append(someDTO.getDate()).toString();

sysout(dummyVal);

Actual result is :

<b>test Id:</b> 123, <b>Type:</b> pend, <b>Date:</b> xx/yy/zz

EXAMPLE: id – 123 , type – pend, date – null

Expected result is like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<b>test Id:</b> 123, <b>Type:</b> pend

Need to ignore the null value tags and to add only tags is not null in java string.

Then Expected result is like:

<b>test Id:</b> 123, <b>Type:</b> pend

>Solution :

This is how conditions are used when using the StringBuffer or StringBuilders in Java applications.
Rewritten your snippet here with conditions.

StringBuffer buffer = new StringBuffer ("<b> test Id </b> ").append(someDTO.getId()).append(", ");

if(Objects.nonNull(someDTO.getType())) {
    buffer.append("<b> Type: </b> ").append(someDTO.getType()).append(", ")
}
if(Objects.nonNull(someDTO.getDate())) {
    buffer.append("<b> Date: </b> ").append(someDTO.getDate()).append(", ");
}
buffer.setLength(buffer.length() - 1); // this is for removing last extra semicolon
String dummyValue = buffer.toString();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading