Best way to verify string is empty or null

前端 未结 13 746
野的像风
野的像风 2020-12-14 15:30

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

相关标签:
13条回答
  • 2020-12-14 15:35

    springframework library Check whether the given String is empty.

    f(StringUtils.isEmpty(str)) {
        //.... String is blank or null
    }
    
    0 讨论(0)
  • 2020-12-14 15:37

    Apache Commons Lang has StringUtils.isEmpty(String str) method which returns true if argument is empty or null

    0 讨论(0)
  • 2020-12-14 15:37

    Simply and clearly:

    if (str == null || str.trim().length() == 0) {
        // str is empty
    }
    
    0 讨论(0)
  • 2020-12-14 15:43

    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'
    }
    
    0 讨论(0)
  • 2020-12-14 15:44

    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.

    0 讨论(0)
  • 2020-12-14 15:46

    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

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