Search code examples
javastringjava-8null

Compare two String in Java with possible null/empty values, when one is null and another is empty it will return true


Looking for a way (OK with using Apache libs as well), to compare two String in Java with possible null/empty values, where the main requirement is when if one is null and another is empty ("") it will return true.

Emphasizing - any null/empty combination allowed, and all the combinations would be considered a true statement.

one   | two  | res
------|------|-----
 ""   | ""   | true
 ""   | null | true
 null | ""   | true
 null | null | true

I've checked many related questions here, and they are not considering my main requirement.


Solution

  • public static boolean isEqual(String one, String two) {
        // org.apache.commons.lang.StringUtils
        return StringUtils.defaultIfEmpty(one, "")
                .equals(StringUtils.defaultIfEmpty(two, ""));
    }
    

    Output:

     one  | two  | res
    ------|------|-----
     ""   | ""   | true
     ""   | null | true
     null | null | true
    

    Alternatives:

    public static boolean isEqual(String one, String two) {
        if (one == null) one = "";
        if (two == null) two = "";    
        return one.equals(two);
    }
    
    public static boolean isEqual(String one, String two) {
        one = Objects.requireNonNullElse(one, "");
        two = Objects.requireNonNullElse(two, "");
        return one.equals(two);
    }