Checking for a not null, not blank String in Java

前端 未结 8 1647
猫巷女王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()
    

提交回复
热议问题