Home > front end >  Clean way to check an empty inside a map in Java
Clean way to check an empty inside a map in Java

Time:10-14

I have a map with data I got from my database and I am having trouble to find an optimal way to check if the value of one of my fields is empty.

The thing is like this. I got 4 values inside a map: A1, A2, A3, and A4. If A4 has data, I just need to return A4, else I return a concatenation of A1, A2, A3.

The thing is that I am trying to check if A4 is empty without transforming it to string (I can always do it, but I have the feeling that there should be a better way to check this).

The query that returns the data is something like this:

String query = "select gactb021.des021, "
                  " gactb032.nif032, gactb032.noc032, gactb032.no032,gactb032.ap1032, gactb032.ap2032, "
                  " sdt031.facto, sdt031.cprof, sdt031.ipago from sdt031 "
                  " INNER JOIN GACTB021 ON sdt031.cacto = GACTB021.act021 "
                  " INNER JOIN GACTB032 ON sdt031.cprof = GACTB032.fact032 "
                  " where NASET = VARIABLE1"
                  " and FACTO <= VARIABLE2 AND FACTO >= VARIABLE3"
                  " AND (SPAGE = 'R'  OR SPAGE = 'M' OR SPAGE = 'F')";

This data is transformed to a List<Map> inside my Java code and in a for loop I retrieve all the info I want.

Here is an example of the function that I currently have:

private static String formatNomFact(Map elements) {
    String issueVar = Objects.toString(elements.get("noc032"), "");
    if(StringUtils.isBlank(issueVar)) { 
        //Do 1
    } else {
        //Do 2
    }
    return "";
}

I would like to know a way to improve my code instead of doing it this way.

CodePudding user response:

You don't need to do any conversion, because (as far as I can tell) at runtime your Map contains a String for that key:

        Object issueVar = elements.get("noc032");
        if (issueVar instanceof String s) {
            if (StringUtils.isEmpty(s)) { //isEmpty checks for null too
                ...
            } else {
                return s;
            }
        } else {
            throw new RuntimeException("Expected String for key noc032 but got '"
                issueVar   "'");
        }
  • Related