getIfEmpty()
?getIfEmpty
is a static method of the StringUtils
class that works as follows.
The method takes in two arguments. One is the character sequence and the other is a supplier instance.
If the given character sequence is empty or null
, then the method returns the value supplied by the supplier.
Otherwise, it returns the given character sequence.
A supplier of Java 8 is a functional interface whose functional method is
get()
. The interface represents an operation that takes no arguments and returns a result.
StringUtils
StringUtils
is defined in the Apache Commons Lang
package. Apache Commons Lang
can be added to the Maven project by adding the following dependency to the pom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the StringUtils
class as follows.
import org.apache.commons.lang3.StringUtils;
public static <T extends CharSequence> T getIfEmpty(final T str, final Supplier<T> defaultSupplier)
final T str
: the string to check
final Supplier <T> defaultSupplier
: the supplier instance
The method returns the passed string or the value returned by the supplier.
"educative"
"hello"
Applying the getIfEmpty
function will result in: educative
. As the given string is not null or empty, the supplied character sequence is returned.
""
"hello"
Applying the getIfEmpty
function will result in: hello
. As the given string is an empty string, the method returns the value returned by the supplier.
null
"hello"
Applying the getIfEmpty
function will result in: hello
. As the given string is null, the method returns the value returned by the supplier.
import org.apache.commons.lang3.StringUtils;public class Main {public static void main(String[] args) {String string = "educative";String returnValue = StringUtils.getIfEmpty(string, () -> "hello");System.out.printf("Value Returned for \"%s\" is \"%s\"", string, returnValue);System.out.println();string = "";returnValue = StringUtils.getIfEmpty(string, () -> "hello");System.out.printf("Value Returned for \"%s\" is \"%s\"", string, returnValue);System.out.println();string = null;returnValue = StringUtils.getIfEmpty(string, () -> "hello");System.out.printf("Value Returned for \"%s\" is \"%s\"", string, returnValue);System.out.println();}}
Value Returned for "educative" is "educative"
Value Returned for "" is "hello"
Value Returned for "null" is "hello"