📜  java coalesce - Java (1)

📅  最后修改于: 2023-12-03 15:31:29.272000             🧑  作者: Mango

Java Coalesce

Coalesce is a Java method that can be used to return the first non-null value in a set of values.

Syntax
public static <T> T coalesce(T... values)

Coalesce method takes a vararg of any number of parameters and returns the first non-null value. The return type is the same as the type of the parameters.

Example
String result = coalesce(null, "Java", "Coalesce");
System.out.println(result); // Output: Java

Integer intResult = coalesce(null, 1, 2, 3);
System.out.println(intResult); // Output: 1
Usage

Coalesce can be used in situations where there are multiple variables to be checked for null before using them, or where a default value needs to be set in case all variables are null.

public void someMethod(String s1, String s2) {
  String value = coalesce(s1, s2, "Default Value");
  // Use the value variable
}
Conclusion

Coalesce is a handy function for reducing null checks and for setting default values. There are also other similar methods such as defaultIfNull available in popular libraries like Apache Commons Lang and Guava.