Java使用或指定默认变量值的最简单方法?

Java使用或指定默认变量值的最简单方法?,java,Java,我从csv文件中读取数据,并希望将列值指定给变量。可能存在文件不包含所需字段的情况。然后我想指定一个默认值。我想要类似的东西: String country = nextLine[columnIndices.get("country")] || "Austria"; 没有很多“如果”的最优雅的方式是什么。(我是C#的java新手)您可以这样做: String country = (nextLine[columnIndices.get("country")] != null) ? nextLin

我从csv文件中读取数据,并希望将列值指定给变量。可能存在文件不包含所需字段的情况。然后我想指定一个默认值。我想要类似的东西:

String country = nextLine[columnIndices.get("country")] || "Austria";

没有很多“如果”的最优雅的方式是什么。(我是C#的java新手)

您可以这样做:

String country = (nextLine[columnIndices.get("country")] != null) ? nextLine[columnIndices.get("country")] : "default";
假设第一个选项不能抛出
NullPointerException
,我建议使用Apache Commons的

它允许您传递任意数量的参数,并将返回第一个not null值

String country = ObjectUtils.firstNonNull(nextLine[columnIndices.get("country")], "Austria");
// Add more arguments if needed

一个简单的if语句可以解决这个问题:

String country = nextLine[columnIndices.get("country")];
if (country == null)
    country = "Austria";

假设您能够使用Java8,那么您可以使用可选的

 Long value = findOptionalLong(ssn).orElse(0L);
这会将值设置为一个数字,如果找不到,则设置为0。

使用以下方法:

private String valueOrDefault(String value, String defaultValue) {
    return value == null ? defaultValue : value; 
}

...

String country = valueOrDefault(nextLine[columnIndices.get("country")], "Austria");

由于Java8,您还可以使用

String s = Optional.ofNullable(fooStr).orElse("bar");
// may be null ----------------^^^^^^

简单易读的一个:

String country = nextLine[columnIndices.get("country")];
country = (country != null) ? country : "Austria";

或者创建一个泛型方法

static <T> T nvl(T first, T ifFirstNull) {
    return (first != null ? first : ifFirstNull);
}
static T nvl(T first,T ifFirstNull){
返回(first!=null?first:ifFirstNull);
}

您可以对任何对象使用它

您可以使用三元运算符哪个部分表示缺少值?是当
columnIndexes.get(“country”)
返回类似-1的值时,还是
nextLine[columnIndexes.get(“country”)]
将包含
null
?此方法唯一的缺点是条件被计算了两次,如果还需要检查空字符串,那么StringUtils.isBlank(str)可能不需要什么apache commons库的方法可能会有所帮助: