Check whether a string is not null and not empty

后端 未结 30 2101
予麋鹿
予麋鹿 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

    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;
    }
    

提交回复
热议问题