I am trying to check if a Java String is not null
, not empty and not whitespace.
In my mind, this code should have been quite up for the job.
With Java 8, you could also use the Optional capability with filtering. To check if a string is blank, the code is pure Java SE without additional library. The following code illustre a isBlank() implementation.
!Optional.ofNullable(tocheck).filter(e -> e != null && e.trim().length() > 0).isPresent()
Optional.ofNullable(toCheck)
.filter(e ->
{
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
})
.isPresent()
You could take a look at JSR 303 Bean Validtion wich contains the Annotatinos @NotEmpty
and @NotNull
. Bean Validation is cool because you can seperate validation issues from the original intend of the method.