What is StringUtils.getIfEmpty in Java?
What is getIfEmpty()?
getIfEmpty is a static method of the StringUtils class that works as follows.
Arguments
The method takes in two arguments. One is the character sequence and the other is a supplier instance.
Return value
-
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.
How to import 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;
Syntax
public static <T extends CharSequence> T getIfEmpty(final T str, final Supplier<T> defaultSupplier)
Parameters
-
final T str: the string to check -
final Supplier <T> defaultSupplier: the supplier instance
Return value
The method returns the passed string or the value returned by the supplier.
Code
Example 1
- string:
"educative" - supplier function returns:
"hello"
Applying the getIfEmpty function will result in: educative. As the given string is not null or empty, the supplied character sequence is returned.
Example 2
- string:
"" - supplier function returns:
"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.
Example 3
- string:
null - supplier function returns:
"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();}}
Output
Value Returned for "educative" is "educative"
Value Returned for "" is "hello"
Value Returned for "null" is "hello"