Java - 检查非空/空否则分配默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31412294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:05:09  来源:igfitidea点击:

Java - Check Not Null/Empty else assign default value

javainlineternary

提问by Cam1989

I am trying to simplify the following code.

我正在尝试简化以下代码。

The basic steps that the code should carry out are as follows:

代码应该执行的基本步骤如下:

  1. Assign String a default value
  2. Run a method
  3. If the method returns a null/empty string leave the String as default
  4. If the method returns a valid string set the String to this result
  1. 为 String 分配默认值
  2. 运行一个方法
  3. 如果该方法返回空/空字符串,则将字符串保留为默认值
  4. 如果该方法返回有效字符串,则将 String 设置为此结果

A Simple example would be:

一个简单的例子是:

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

I have made another attemp using a ternary operator:

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

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

The isNotNullOrEmpty() Method

isNotNullOrEmpty() 方法

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

Is it possible to do all of this in-line? I know I could do something like this:

是否可以在线完成所有这些操作?我知道我可以做这样的事情:

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

But I am calling the same method twice. I would be something like to do something like this (which doesn't work):

但我两次调用相同的方法。我会做这样的事情(这不起作用):

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

I would like to initialize the 'temp' String within the same line. Is this possible? Or what should I be doing?

我想在同一行中初始化“临时”字符串。这可能吗?或者我应该怎么做?

Thank you for your suggestions.

谢谢你的建议。

Tim

蒂姆

采纳答案by Shibashis

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

回答by Jon Skeet

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 needtemp... you've effectively used the method parameter as a way of initializing the temporary variable.

此时,您不需要temp……您已经有效地使用了方法参数作为初始化临时变量的一种方式。

If you reallywant tempand you don't want an extra method, you cando it in one statement, but I really wouldn't:

如果你真的想要temp并且你不想要一个额外的方法,你可以在一个语句中完成,但我真的不会:

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

回答by nobeh

Use Java 8 Optional(no filter needed):

使用 Java 8 Optional(不需要过滤器):

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

回答by zalis

Use org.apache.commons.lang3.StringUtils

使用 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

默认

默认

回答by Tarik

You can use this method in the ObjectUtilsclass from org.apache.commons.lang3library :

您可以在org.apache.commons.lang3库中的ObjectUtils类中使用此方法:

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

回答by AK4647

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

如果使用 JDK 9+,请使用 Objects.requireNonNullElse(T obj, T defaultObj)

回答by lights

With guava you can use

使用番石榴,您可以使用

MoreObjects.firstNonNull(possiblyNullString, defaultValue);