Check whether a string is not null and not empty

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

    With Java 8 Optional you can do:

    public Boolean isStringCorrect(String str) {
        return Optional.ofNullable(str)
                .map(String::trim)
                .map(string -> !str.isEmpty())
                .orElse(false);
    }
    

    In this expression, you will handle Strings that consist of spaces as well.

提交回复
热议问题