Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.isBlank() replacement

Tags:

java

I'm trying to adapt a code which uses String.isBlank(text). This method was introduced in Java 11, but my current project uses Java 8 and I don't want to upgrade. Is there anywhere the source code of the isBlank method or how can I replace it?

I tried make a method but I'm not sure what check should I put in there:

/**
 * @param text - the text to check
 * @return {@code true} if {@code text} is empty or contains only white space codepoints
 */
public static final boolean isBlank(final String text)
{
    if (text == null || text.isEmpty())
    {
        return true;
    }
    
    for (final char c : text.toCharArray())
    {
        //Check here
    }
    
    return false;
}
like image 829
KbantikiMixaniki Avatar asked Jun 13 '26 20:06

KbantikiMixaniki


1 Answers

In the class org.apache.commons.lang3.StringUtils, the function isBlank is like this:

public static boolean isBlank(final CharSequence cs) {
    int strLen;
    if (cs == null || (strLen = cs.length()) == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if (!Character.isWhitespace(cs.charAt(i))) {
            return false;
        }
    }
    return true;
}

It works well for Java 8, you just have to import it

like image 94
TheTisiboth Avatar answered Jun 17 '26 23:06

TheTisiboth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!