Tuesday 31 January 2012

Apache Commons Lang StringUtils

So, thought it'd be good to talk about another Java library that I like. It's been around for a while and is not perhaps the most exciting library, but it is very very useful. I probably make use of it daily.

org.apache.commons.lang.StringUtils

StringUtils is part of Apache Commons Lang (http://commons.apache.org/lang/, and as the name suggest it provides some nice utilities for dealing with Strings, going beyond what is offered in java.lang.String. It consists of over 50 static methods, and I'm not going to cover every single one of them, just a selection of methods that I make the most use of.

There are two different versions available, the newer org.apache.commons.lang3.StringUtils and the older org.apache.commons.lang.StringUtils. There are not really any significant differences between the two. lang3.StringUtils requires Java 5.0 and is probably the version you'll want to use.



public static boolean equals(CharSequence str1, CharSequence str2)

Thought I'd start with one of the most straight forward methods. equals. This does exactly what you'd expect, it takes two Strings and returns true if they are identical, or false if they're not.

But java.lang.String already has a perfectly good equals method? Why on earth would I want to use a third party implementation?

It's a fair question. Let's look at some code, can you see any problems?

public void doStuffWithString(String stringParam) {
    if(stringParam.equals("MyStringValue")) {
        // do stuff
    }
}

That's a NullPointerException waiting to happen!

There are a couple of ways around this:

public void safeDoStuffWithString1(String stringParam) {
    if(stringParam != null && stringParam.equals("MyStringValue")) {
        // do stuff
    }
}

public void safeDoStuffWithString2(String stringParm) {
    if("MyStringValue".equals(stringParam)) {
        // do stuff
    }
}

Personally I'm not a fan of either method. I think null checks pollute code, and to me "MyStringValue".equals(stringParam) just doesn't scan well, it looks wrong.

This is where StringUtils.equals comes in handy, it's null safe. It doesn't matter what you pass it, it won't NullPointer on you! So you could rewrite the simple method as follows:

public void safeDoStuffWithString3(String stringParam) {
    if(StringUtils.equals(stringParam,"MyStringValue)) {
        // do stuff
    }
}

It's personal preference, but I think this reads better than the first two examples. There's nothing wrong with them, but I do think StringUtils.equals() is worth considering.



isEmpty, isNotEmpty, isBlank, isNotBlank

OK, these look pretty self explanatory, I'm guessing they're all null safe?

You're probably spotting a pattern here. isEmpty is indeed a null safe replacement for java.lang.String.isEmpty(), and isNotEmpty is it's inverse. So no more null checks:

  if(myString != null && !myString.isEmpty()) { // urghh
     // Do stuff with myString
  }

  if(StringUtils.isNotEmpty(myString)) { // much nicer
     // Do stuff with myString
  }

So, why Blank and Empty?

There is a difference, isBlank also returns true if the String just contains whitespace, ie...

  String someWhiteSpace = "    \t  \n";
  StringUtils.isEmpty(someWhiteSpace); // false
  StringUtils.isBlank(someWhiteSpace); // true


public static String[] split(String str, String separatorChars)

Right that looks just like String.split(), so this is just a null safe version of the built in Java method?

Well, yes it certainly is null safe. Trying to split a null string results in null, and a null separator splits on whitespace. But there is another reason you should consider using StringUtils.split(...), and that's the fact that java.lang.String.split takes a regular expression as a separator. For example the following may not do what you want:

public void possiblyNotWhatYouWant() {
    String contrivedExampleString = "one.two.three.four";
    String[] result = contrivedExampleString.split(".");
    System.out.println(result.length); // 0
}
But all I have to do is put a couple of backslashes in front of the '.' and it will work fine. It's not really a big deal is it?

Perhaps not, but there's one last advantage to using StringUtils.split, and that's the fact that regular expressions are expensive. In fact when I tested splitting a String on a comma (a fairly common use case in my experience), StingUtils.split runs over four times faster!



public static String join(Iterable iterable, String separator)

Ah, finally something genuinely useful!

Indeed I've never found an elegant way of concatenating strings with a separator, there's always that annoying conditional require to check if want to insert the separator or not. So it's nice there's a utility to this for me. Here's a quick example:

  String[] numbers = {"one", "two", "three"};
  StringUtils.join(numbers,",");  // returns "one,two,three"

There's also various overloaded versions of join that take Arrays, and Iterators.

Ok, I'm convinced. This looks like a pretty useful library, what else can it do?

Quite a lot, but like I said earlier I won't bother going through every single method available, I'd just end up repeating what's said in the API documentation. I'd really recommend taking a closer look: http://commons.apache.org/lang/api-3.1/org/apache/commons/lang3/StringUtils.html

So basically if you ever need to do something with a String that isn't covered by Java's core String library (and maybe even stuff that is), take a look at StringUtils.

26 comments:

Tomáš Záluský said...

I personally prefer Guava over commons-lang. Splitting and joining are IMHO more powerful and helper methods like emptyToNull etc. are more universal.
However commons-lang is awesome for specific use cases like Levenshtein distance or very powerful ToStringBuilder + ToStringStyle API.

Eric Jablow said...

Java 7 has an Objects class with a method with signature

public static boolean equals(Object a, Object b)

This makes StringUtils.equals(String a, String b) unnecessary. However, programmers should ask why they are allowing nulls in the first place. Sometimes it can't be helped, but sometimes it's just laziness.

Unknown said...

I think I'll stick with commons-lang3 primarily for the ToStringBuilder API which provide some useful shortcuts for debugging.

aliyaa said...

You must have personal statement editing services because it will edit your errors and help you in writing best statement.

paulsmith198914@gmail.com said...

Are there two different versions available? I wouldn't know this. The best cheap essay writing service is here to help you complete your academic task.

Curtis said...

I'd like to understand all the available versions. Maybe you should have engaged us more on that. Anyway, thanks a lot for sharing. write my essay

writing tips said...

Awesome! Education is the extreme motivation that open the new doors of data and material. So we always need to study around the things and the new part of educations with that we are not mindful.
dissertation Writing Services

nish gau said...

xbox live codes generator
free xbox live codes unused
free xbox gift card codes

meldaresearchusa said...

Our Already Written Essay writers have been 14 years experience in the field where they have assisted thousands of returning clients in attaining high scores.

meldaresearchusa said...

Our buy Essay Cheap services are focused on making your life in school smooth and enjoyable in comparison to what you might be going through at the moment.

meldaresearch said...

Our custom dissertation writing help services come to your rescue so that you can enjoy school life to the fullest without having to worry about your assignments.We try our best to provide all our clients with what they deserve in their legitimate essay writing service work.

Ivymelda said...

Our writers are always available to help students with Urgent Essay Writing Service; hence, any student looking to Non Plagiarized Essays can request for our services at anytime.

James Charlie said...

A little more of research could have strengthened the paper even further. However, worry no more, as the experts at myassignmenthelpau.com are here to offer you necessary Marketing Assignment Help guidance with assignments of all types including thesis, essay, dissertation and more.

ol said...

Decent post! Its truly fascinating. The thoughts were acceptable and supportive to us. I recommend Dissertation Writing Service to maintain the quality of your writing skills.

Kaylee Brown said...

Hiring a qualified and experienced Java programming assignment help relieve you of your load while also assisting you in producing an accurate and professional assessment paper that will earn you an A. However, it is totally up to you whether you choose any religious writing service to relieve you of all of your worries while also guaranteeing a high-quality assessment or simply wind up with a low-impacting paper.

Antony Christ said...


It was nice to read your blog. If anyone needs any type of case study and assignment help at the cheapest price then visit our website:- My Case Study Help. We are the best Assignment Help Australia website, provide all types of services for MBA Assignment Help, Nursing Case Study Help, Law Case Study Help and Engineering students. Avail Assignment Writing Service with the world's most trusted and no1 company for Case Study and Assignment Help in Australia. Get professionally prepared assignments by our amazing Case Study Writers with 100% quality check and plagiarism-free paper.

Shivam Kumar said...

You have done nice job . Keep it up .you can visit stringutils isnotblank and stringutils isnotempty method examples with nice explanation .

EricFord said...

Nice piece of code with good suggestions which make this blog attractive for students as well as developers too, share more like this Now it's time to avail HALFCASTE CREAM SET for more information.

John Hardy said...

Such a great blog. You are not going to cover every single one of them just a selection of methods that. I make the most use of. Now it's time to avail HALFCASTE CREAM SET for more information.

alex blake said...

what an educational stuff it is as you are telling about the programming things through your blogs its quiet helpful for students like me i surely use this in my assignment and the rest of information i have found on process essay help service. this is such a great platform to gain information.

David said...

Such a nice article. Good information tom's programming. Its very useful blog. Your thoughts and learning easy programming. I probably make use for it daily. Now it's time to get interior demolition for more information.

Ali said...

Thanks to your blogs. I always found them helpful for me in my projects. Now get the best services of Home Tutors in Lahore, Click for more information.

Tom John said...

What a lovely written piece. Tom's programming contains useful information. This is a very useful blog. Your ideas and learning simple programming. I'm sure I use it on a daily basis. Its time to avail of the service of Best Dermatologist/Skin Specialist in Lahore,click Here .

ownsmitjh said...

I read this informative blog. This is very helpful and useful for us. Your writing technique is impressive and enjoyable to read. Thanks for sharing this content with us. Now it's time to get limo rental surprise az for more information.

Sophia Daniel said...

I personally use this, and this is one of the powerful tool. All the points are very amazing and valid. Tom's programming is an informative article. Thankyou for sharing. Now its time to avail Car Services in Orlando for more information.

Gary sobers said...

I was searching to read that kind of article and I finally found it. I am very happy to see your article after a long time. Nice post. Now its time to avail roller shutter repairs for more information.