[Java] StringUtils.defaultIfEmpty() 判斷空值並直接回傳預設值
StringUtils.defaultIfEmpty(String str, String defaultStr)
如果空值,則回傳預設 defaultStr
str = "" → return defaultStr
str != "" → return str
例子:
String str, defaultStr, result;
str = "";
defaultStr = "123";
result = StringUtils.defaultIfEmpty(str, defaultStr); //123
str = "abc";
defaultStr = "123";
result = StringUtils.defaultIfEmpty(str, defaultStr); //abc
以往:
String str, defaultStr, result; str = "";
defaultStr = "123";
if (str.equals("")) result = defaultStr; //123
else result = str;
str = "abc";
defaultStr = "123";
if (str.equals("")) result = defaultStr;
else result = str; //abc
defaultIfEmpty() 原始碼:
public static <T extends CharSequence> T defaultIfEmpty(T str, T defaultStr)
{
return isEmpty(str) ? defaultStr : str;
}
留言
張貼留言