Home > Back-end >  How to simplify this java for each loop?
How to simplify this java for each loop?

Time:10-14

I'm trying to simplify the following code.

while(results.next())
    for(String column : colNames){
        if(EmptyUtil.isEmpty(results.getString(column))) {
            emptyCount  ;
        }
    }
    
    if(emptyCount == colNames.size()){
        break;
    }
}

My main goal is to read a CSV file until an empty row and finish reading the file from there. And it's a necessity that I have to use this Csvjdbd driver ).

In the above code, results is a CsvResultSet (I've used Csvjdbc library to get this result set ). This CsvResultSet represents a single row in the CSV file inside the for loop. Basically I'm going through every row in the CSV file b colNames is the column headers list in the CSV. By using results.toString(column), I can get the value in the particular cell in the row.

If all the cells are empty in the row, I should break from the while loop.

The above code works as expected. I just need to know how to simplify that more.

CodePudding user response:

Try this.

L: while(results.next()) {
    for(String column : colNames){
        if(!EmptyUtil.isEmpty(results.getString(column))) {
            continue L;
        }
    }
    break;
}

CodePudding user response:

Not sure this is much simpler, but perhaps more readable:

while (results.next() && !allColumnsEmpty(results, colNames)) {
}

...

private boolean allColumsEmpty(ResultSet results, String...colNames) {
    for(String column : colNames){
        if(!EmptyUtil.isEmpty(results.getString(column))) {
            return false;
        }
    }
    return true;
}

CodePudding user response:

I would use Stream API to decide, and an external variable instead of break.

boolean wasEmptyRow = false;
while (!wasEmptyRow && results.next()) {
    wasEmptyRow = colNames
        .stream()
        .map(column -> results.getString(column))
        .allMatch(EmptyUtil::isEmpty);
    if (! wasEmptyRow) {
        // process
    }
}

You simply create a stream from the column names, replace all values with the current value from the result, then check if all of them are empty. The allMatch is optimized, it will not check all columns if one failing case was found. This saves the break for you.

  • Related