Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set null value if String is empty?

Sometimes developers checks if Strings are null values, if yes, sets those Strings as empty value:

if (text == null) {
    text = "";
}

What I want to do is to write opposite if statement:

if (text.isEmpty()) {
    text = null;
}

But...first of all - I have to check (as usually) if this String is null to avoid NullPointerException, so right now it looks like this (very ugly but KISS):

if (!text == null) {
    if (text.isEmpty()) {
        text = null;
    }
}

My class has several String fields and for all of them I have to prepare this solution. Any basic ideas for more efficient code? Is it a good way to strech it to lambda expressions and iterate throught all String fields in this class?

like image 909
designuj Avatar asked Aug 25 '26 11:08

designuj


1 Answers

Another alternative using Guava's emptyToNull:

text = Strings.emptyToNull(text);
like image 130
Vadzim Avatar answered Aug 28 '26 01:08

Vadzim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!