Check whether a string is not null and not empty

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

    In case you are using Java 8 and want to have a more Functional Programming approach, you can define a Function that manages the control and then you can reuse it and apply() whenever is needed.

    Coming to practice, you can define the Function as

    Function isNotEmpty = s -> s != null && !"".equals(s)
    

    Then, you can use it by simply calling the apply() method as:

    String emptyString = "";
    isNotEmpty.apply(emptyString); // this will return false
    
    String notEmptyString = "StackOverflow";
    isNotEmpty.apply(notEmptyString); // this will return true
    

    If you prefer, you can define a Function that checks if the String is empty and then negate it with !.

    In this case, the Function will look like as :

    Function isEmpty = s -> s == null || "".equals(s)
    

    Then, you can use it by simply calling the apply() method as:

    String emptyString = "";
    !isEmpty.apply(emptyString); // this will return false
    
    String notEmptyString = "StackOverflow";
    !isEmpty.apply(notEmptyString); // this will return true
    

提交回复
热议问题