Java-勾选 Not Null/Empty else 赋予默认值

我试图简化以下代码。

守则应执行的基本步骤如下:

  1. 为 String 分配一个默认值
  2. 运行一个方法
  3. 如果方法返回一个空/空字符串,那么保留 String 作为默认值
  4. 如果该方法返回有效的字符串,则将 String 设置为此结果

一个简单的例子是:

    String temp = System.getProperty("XYZ");
String result = "default";
if(temp != null && !temp.isEmpty()){
result = temp;
}

我使用三元运算符进行了另一次尝试:

    String temp;
String result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";

IsNotNullOrEmpty ()方法

 private static boolean isNotNullOrEmpty(String str){
return (str != null && !str.isEmpty());
}

有没有可能做到这一切? 我知道我可以这样做:

String result = isNotNullOrEmpty(System.getProperty("XYZ")) ? System.getProperty("XYZ") : "default";

但是我要调用同一个方法两次。我会像这样做一些事情(这不工作) :

String result = isNotNullOrEmpty(String temp = System.getProperty("XYZ")) ? temp : "default";

我想在同一行中初始化‘ temp’String。这可能吗?或者我应该做什么?

谢谢你的建议。

提姆

173611 次浏览

Sounds like you probably want a simple method like this:

public String getValueOrDefault(String value, String defaultValue) {
return isNotNullOrEmpty(value) ? value : defaultValue;
}

Then:

String result = getValueOrDefault(System.getProperty("XYZ"), "default");

At this point, you don't need temp... you've effectively used the method parameter as a way of initializing the temporary variable.

If you really want temp and you don't want an extra method, you can do it in one statement, but I really wouldn't:

public class Test {
public static void main(String[] args) {
String temp, result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";
System.out.println("result: " + result);
System.out.println("temp: " + temp);
}


private static boolean isNotNullOrEmpty(String str) {
return str != null && !str.isEmpty();
}
}

Use Java 8 Optional (no filter needed):

public static String orElse(String defaultValue) {
return Optional.ofNullable(System.getProperty("property")).orElse(defaultValue);
}

Use org.apache.commons.lang3.StringUtils

String emptyString = new String();
result = StringUtils.defaultIfEmpty(emptyString, "default");
System.out.println(result);


String nullString = null;
result = StringUtils.defaultIfEmpty(nullString, "default");
System.out.println(result);

Both of the above options will print:

default

default

I know the question is really old, but with generics one can add a more generalized method with will work for all types.

public static <T> T getValueOrDefault(T value, T defaultValue) {
return value == null ? defaultValue : value;
}

You can use this method in the ObjectUtils class from org.apache.commons.lang3 library :

public static <T> T defaultIfNull(T object, T defaultValue)

If using JDK 9 +, use Objects.requireNonNullElse(T obj, T defaultObj)

With guava you can use

MoreObjects.firstNonNull(possiblyNullString, defaultValue);

This is the best solution IMHO. It covers BOTH null and empty scenario, as is easy to understand when reading the code. All you need to know is that .getProperty returns a null when system prop is not set:

String DEFAULT_XYZ = System.getProperty("user.home") + "/xyz";
String PROP = Optional.ofNullable(System.getProperty("XYZ"))
.filter(s -> !s.isEmpty())
.orElse(DEFAULT_XYZ);

In Java 9, if you have an object which has another object as property and that nested objects has a method yielding a string, then you can use this construct to return an empty string if the embeded object is null :

String label = Optional.ofNullable(org.getDiffusion()).map(Diffusion::getLabel).orElse("")

In this example :

  • org is an instance of an object of type Organism
  • Organism has a Diffusion property (another object)
  • Diffusion has a String label property (and getLabel() getter).

With this example, if org.getDiffusion() is not null, then it returns the getLabel property of its Diffusion object (this returns a String). Otherwise, it returns an empty string.

If you need to set not null value or return default value instead you can use simple generic method

private <T> T getIfNotNullOrElse(T input, T data) {
return Optional.ofNullable(input).orElse(data);
}