Search code examples
javajava-8nullstringbuilder

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:

<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());
    
    if(Objects.nonNull(someDTO.getType())) {
        buffer.append(", ").append("<b> Type: </b> ").append(someDTO.getType());
    }
    if(Objects.nonNull(someDTO.getDate())) {
        buffer.append(", ").append("<b> Date: </b> ").append(someDTO.getDate());
    }
    //buffer.setLength(buffer.length() - 1); // this is updated as per Holger's comment
    String dummyValue = buffer.toString();