Checking for a not null, not blank String in Java

前端 未结 8 1633
猫巷女王i
猫巷女王i 2021-01-31 13:24

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.

         


        
相关标签:
8条回答
  • 2021-01-31 14:22

    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.

    String.trim() behaviour

    !Optional.ofNullable(tocheck).filter(e -> e != null && e.trim().length() > 0).isPresent()
    

    StringUtils.isBlank() behaviour

    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()
    
    0 讨论(0)
  • 2021-01-31 14:28

    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.

    0 讨论(0)
提交回复
热议问题