Best way to verify string is empty or null

前端 未结 13 745
野的像风
野的像风 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: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 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.

提交回复
热议问题