Dusan Vagasky Dusan Vagasky - 5 months ago 10
Java Question

I have to check if parameters exist, if yes add '':'' between them


  • if parameter parent_Id exist separate them with : (parent_Id:leadingNumber)

  • if parameter does not exist, there will be only leadingNumber without :

  • if parameter is empty, there will be only leadingNumber without :

  • (nullpointer)



This is the existing code:

private void mapLeadingNumber() throws Exception
{
if ( logger.isDebugEnabled() ) logger.debug( "[" + this.orderId + "] mapLeadingNumber HTS - start" );

String leadingNumber = "";

try
{
Product[] products = this.order.mapProducts("LeadingNumber", null, "LeadingNumberAttribute");
for (int i=0; i<products.length; i++)
{
Product htsProduct = products[i];
if (htsProduct.getAttribute().length > 0)
{
leadingNumber = htsProduct.getAttribute()[0].getAttributeValue();
this.spcRequest.getSpcRequest().addNewNpstnLeadingNumberAvail().setNpstnLeadingNumberPtr(leadingNumber);
}
}
if ( logger.isDebugEnabled() ) logger.debug( "[" + this.orderId + "] mapLeadingNumber HTS mapped value " + leadingNumber );
}

catch (Exception e)
{
throw new MappingException("Exception in mapLeadingNumber: " + e.getMessage(), e);
}

if ( logger.isDebugEnabled() ) logger.debug( "[" + this.orderId + "] mapLeadingNumber HTS - end" );

String parent_Id = "";

try
{
Product[] products = this.order.mapProducts("Parent_Id", null, "Parent_IdAttribute");
for (int i=0; i<products.length; i++)
{
Product htsProduct = products[i];
if (htsProduct.getAttribute().length > 0)
{
parent_Id = htsProduct.getAttribute()[0].getAttributeValue();
this.spcRequest.getSpcRequest().addNewNpstnLeadingNumberAvail().setNpstnLeadingNumberPtr(parent_Id);
}
}
if ( logger.isDebugEnabled() ) logger.debug( "[" + this.orderId + "] mapLeadingNumber HTS mapped value " + parent_Id );
}

catch (Exception e)
{
throw new MappingException("Exception in mapLeadingNumber: " + e.getMessage(), e);
}

if ( logger.isDebugEnabled() ) logger.debug( "[" + this.orderId + "] mapLeadingNumber HTS - end" );

}

Answer

You could use something like:

public static void main(String [] args) {
    String parentId = "parentId";
    String leadingNumber = "leadingNumber";
    System.out.println(join(parentId, leadingNumber));
    parentId = null;
    System.out.println(join(parentId, leadingNumber));
    parentId = "";
    System.out.println(join(parentId, leadingNumber));
}

public static String join(String parentId, String leadingNumber) {
    List<String> list = (List<String>)Arrays.asList(new String[]{parentId, leadingNumber}).stream().filter(s -> s != null && s != "").collect(Collectors.toList());
    return String.join(":", list);
}
Comments