Skip to content
Advertisement

Checking null for multiple strings in Java

How can one check for whether one of the strings is not null, only if the rest contain something?

Here is an example of how it works, but I feel like there should be a better way to do it.

if ((string1 != null && !string1.equals("")) && 
    (string2 == null || string2.equals("") || string3 == null || string3.equals(""))) {
        // BAD
} else if ((string2 != null && !string2.equals("")) &&
    (string1 == null || string1.equals("") || string3 == null || string3.equals(""))) {
        // BAD
} else if ((string3 != null && !string3.equals("")) &&
    (string1 == null || string1.equals("") || string2 == null || string2.equals(""))) {
        // BAD
}

Is there a way to condense this logic into a better approach?

EDIT

If all strings are null, that’s fine.

If all string aren’t null, also fine.

If at least one is not null and at least one is null, not fine.

SAMPLE

public static void main(String []args){
     
    String string1 = "1";
    String string2 = "2";
    String string3 = "3";

    String stringA = "";
    String stringB = "";
    String stringC = "";

    String stringQ = "1";
    String stringW = "2";
    String stringY = "";

    // THIS IS FINE         
    System.out.println(isGood(string1, string2, string3));

    // THIS IS FINE         
    System.out.println(isGood(stringA, stringB, stringC));

    // THIS IS NOT FINE         
    System.out.println(isGood(stringQ, stringW, stringY));

}
 
public static boolean isGood (String ... strings) {

    long nullCount = Arrays.stream(strings)
        .filter(s -> s == null || s.isEmpty())
        .count();

    return strings.length == nullCount || nullCount == 0;
}

Advertisement

Answer

Based on what I understood of your requirements in the comments this should work.

Count the number of null (or non null, either way works). Then compare that with the amount of strings passed into the method. If the count is neither the length of the list or 0 then it means there is a mix of not null or empty string vs null or empty strings (indicating it’s bad).

public static boolean badStrings (String ... strings) {

    var nullCount = Arrays.stream(strings)
            .filter(s -> s == null || s.isEmpty())
            .count();

    return nullCount < strings.length && nullCount > 0;
}

Note that count returns long and length method of array will return an int.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement