Search code examples
javaarraysstringperformanceif-statement

Change value of String without if statement


I need to transform a few values of a String array (String []) to Int and i would like to do it avoiding unnecesary code if possible.

Here is an example of what i do.

I read a line of a CSV file Example:

11;;000000000000000;2023-01-01;000;600;021;3008577;*********C;OPTIONAL;1005698;555;25;43;59999;0.00;0.00;0.00;S
;********E;000000000000000;2023-01-01;000;600;021;3008577;*********C;OPTIONAL;1005698;555;25;43;59999;0.00;0.00;0.00;N

And I do this (reading of the file is not important so let´s skip that):

     for (String fileSingleLine: contentFile) {
                String[] line = fileSingleLine.split(";");
                finalContent.append(customDTO.setLineValues(line).append("/n");
     }
 

Inside of my evaluator I need to transform the first value that can be a number or and empty String to int with a simple

Integer.valueOf(line[0]) 

This obviously throws a NumberFormatException so i would have to check first if the string isEmpty and do this:

int values;

if(line[O].isEmpty()) {
        values = 0;
} else {
        values = Integer.valueOf(line[0]);
}

Is there any way to do this avoiding ternary operators and if else statement?


PD: After doing a few benchmarks with files with over 100K lines i have around a 30% improvement using the concat option instead of the if-else one. The only change in the code that i applied between both tries is the following one:

//        if (StringUtils.isBlank(line[0])) {
//            contenido.append(Integer.valueOf("0")); 
//        } else {
//            contenido.append(Integer.valueOf(line[0]));
//        }
        
        contenido.append(Integer.valueOf("0".concat(line[0]).trim()));

filewise the order between first objects been empties and having value is random to avoid the predictor algorithm.


Solution

  • There are two ways i can think of to do it without if-else or ternary. But i wouldn't recommend anyone using them. They are just to feed the curiosity.

    1. Using try-catch

    int values;
    try {
        values = Integer.parseInt(line[0]);
    } catch (NumberFormatException e) {
        values = 0;
    }
    System.out.println(values); 
    

    2. String concat

    int values = Integer.parseInt(line[0]+"0")/10;
    System.out.println(values);
    

    The 0 is appended at last so that negative numbers don't cause any problem.