Check whether a string is not null and not empty

后端 未结 30 2094
予麋鹿
予麋鹿 2020-11-22 02:13

How can I check whether a string is not null and not empty?

public void doStuff(String str)
{
    if (str != null && str != \"**here I want to check          


        
相关标签:
30条回答
  • 2020-11-22 02:45

    To add to @BJorn and @SeanPatrickFloyd The Guava way to do this is:

    Strings.nullToEmpty(str).isEmpty(); 
    // or
    Strings.isNullOrEmpty(str);
    

    Commons Lang is more readable at times but I have been slowly relying more on Guava plus sometimes Commons Lang is confusing when it comes to isBlank() (as in what is whitespace or not).

    Guava's version of Commons Lang isBlank would be:

    Strings.nullToEmpty(str).trim().isEmpty()
    

    I will say code that doesn't allow "" (empty) AND null is suspicious and potentially buggy in that it probably doesn't handle all cases where is not allowing null makes sense (although for SQL I can understand as SQL/HQL is weird about '').

    0 讨论(0)
  • 2020-11-22 02:45

    You should use org.apache.commons.lang3.StringUtils.isNotBlank() or org.apache.commons.lang3.StringUtils.isNotEmpty. The decision between these two is based on what you actually want to check for.

    The isNotBlank() checks that the input parameter is:

    • not Null,
    • not the empty string ("")
    • not a sequence of whitespace characters (" ")

    The isNotEmpty() checks only that the input parameter is

    • not null
    • not the Empty String ("")
    0 讨论(0)
  • 2020-11-22 02:45

    Simple solution :

    private boolean stringNotEmptyOrNull(String st) {
        return st != null && !st.isEmpty();
    }
    
    0 讨论(0)
  • 2020-11-22 02:45

    In case you need to validate your method parameters you can use follow simple method

    public class StringUtils {
    
        static boolean anyEmptyString(String ... strings) {
            return Stream.of(strings).anyMatch(s -> s == null || s.isEmpty());
        }
    
    }
    

    Example:

    public String concatenate(String firstName, String lastName) {
        if(StringUtils.anyBlankString(firstName, lastName)) {
            throw new IllegalArgumentException("Empty field found");
        }
        return firstName + " " + lastName;
    }
    
    0 讨论(0)
  • 2020-11-22 02:48

    As seanizer said above, Apache StringUtils is fantastic for this, if you were to include guava you should do the following;

    public List<Employee> findEmployees(String str, int dep) {
     Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
     /** code here **/
    }
    

    May I also recommend that you refer to the columns in your result set by name rather than by index, this will make your code much easier to maintain.

    0 讨论(0)
  • 2020-11-22 02:48

    If you are using Spring Boot then below code will do the Job

    StringUtils.hasLength(str)
    
    0 讨论(0)
提交回复
热议问题