getIfBlank
is a static method of the StringUtils
class that works as follows:
Note:
Supplier
in Java 8 is a functional interface whose functional method isget()
. The interface represents an operation that takes no arguments and returns a result.
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>
Note: 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 getIfBlank(T str, Supplier<T> defaultSupplier)
T str
: the string to checkSupplier<T> defaultSupplier
: the supplier instanceThe method returns the passed string or 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.getIfBlank(string, () -> "hello");System.out.printf("Value Returned for \"%s\" is \"%s\"", string, returnValue);System.out.println();string = "";returnValue = StringUtils.getIfBlank(string, () -> "hello");System.out.printf("Value Returned for \"%s\" is \"%s\"", string, returnValue);System.out.println();string = null;returnValue = StringUtils.getIfBlank(string, () -> "hello");System.out.printf("Value Returned for \"%s\" is \"%s\"", string, returnValue);System.out.println();string = " ";returnValue = StringUtils.getIfBlank(string, () -> "hello");System.out.printf("Value Returned for \"%s\" is \"%s\"", string, returnValue);System.out.println();}}
"educative"
"hello"
The getIfBlank
function returns educative
.
Since the given string is not whitespace, null, or empty, the supplied character sequence is returned.
""
"hello"
The getIfBlank
function returns hello
.
Since the given string is an empty string, the method returns the value returned by the supplier.
null
"hello"
The getIfBlank
function returns hello
.
Since the given string is null
, the method returns the value returned by the supplier.
" "
"hello"
The getIfBlank
function returns hello
.
Since the given string only has whitespace characters, the method returns the value returned by the supplier.
Value Returned for "educative" is "educative"
Value Returned for "" is "hello"
Value Returned for "null" is "hello"
Value Returned for " " is "hello"