如何在 Java 中获取第一个非空值? [英] How to get the first non-null value in Java?
问题描述
是否有与 SQL 的 COALESCE
函数等效的 Java 函数?即有没有办法返回几个变量的第一个非空值?
Is there a Java equivalent of SQL's COALESCE
function? That is, is there any way to return the first non-null value of several variables?
例如
Double a = null;
Double b = 4.4;
Double c = null;
我想以某种方式有一个语句来返回 a
、b
和 c
的第一个非空值 - 在这个在这种情况下,它将返回 b
或 4.4.(类似于 sql 方法 - 返回 COALESCE(a,b,c)
).我知道我可以通过以下方式明确地做到这一点:
I want to somehow have a statement that will return the first non-null value of a
, b
, and c
- in this case, it would return b
, or 4.4. (Something like the sql method - return COALESCE(a,b,c)
). I know that I can do it explicitly with something like:
return a != null ? a : (b != null ? b : c)
但我想知道是否有任何内置的、可接受的函数来实现这一点.
But I wondered if there was any built-in, accepted function to accomplish this.
推荐答案
不,没有.
你能得到的最接近的是:
The closest you can get is:
public static <T> T coalesce(T ...items) {
for(T i : items) if(i != null) return i;
return null;
}
出于有效的原因,您可以按以下方式处理常见情况:
For efficient reasons, you can handle the common cases as follows:
public static <T> T coalesce(T a, T b) {
return a == null ? b : a;
}
public static <T> T coalesce(T a, T b, T c) {
return a != null ? a : (b != null ? b : c);
}
public static <T> T coalesce(T a, T b, T c, T d) {
return ...
}
这篇关于如何在 Java 中获取第一个非空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!