i am sure this must have been asked before in different ways - as isEmptyOrNull is so common yet people implement it differently. but i have below curious query in terms of
springframework library Check whether the given String is empty.
f(StringUtils.isEmpty(str)) {
//.... String is blank or null
}
Apache Commons Lang has StringUtils.isEmpty(String str)
method which returns true if argument is empty or null
if (str == null || str.trim().length() == 0) {
// str is empty
}
This one from Google Guava could check out "null and empty String" in the same time.
Strings.isNullOrEmpty("Your string.");
Add a dependency with Maven
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
with Gradle
dependencies {
compile 'com.google.guava:guava:20.0'
}
If you have to test more than one string in the same validation, you can do something like this:
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class StringHelper {
public static Boolean hasBlank(String ... strings) {
Predicate<String> isBlank = s -> s == null || s.trim().isEmpty();
return Optional
.ofNullable(strings)
.map(Stream::of)
.map(stream -> stream.anyMatch(isBlank))
.orElse(false);
}
}
So, you can use this like StringHelper.hasBlank("Hello", null, "", " ")
or StringHelper.hasBlank("Hello")
in a generic form.
You can make use of Optional and Apache commons Stringutils library
Optional.ofNullable(StringUtils.noEmpty(string1)).orElse(string2);
here it will check if the string1 is not null and not empty else it will return string2