What's the best way to build a string of delimited items in Java?
Join strings seamlessly with StringJoiner
in Java 8:
Outside the realm of Java 8, StringBuilder
is your reliable workhorse:
Simpler join with String.join
and TextUtils.join
When using collections, Java 8 pulled a rabbit out of its hat with String.join
:
For the Android aficionados, Android's TextUtils.join
has got you covered:
Looking beyond Java? The handy StringUtils.join
function from Apache Commons Lang library has your back:
Nulls and empty lists: Uninvited guests, anyone?
Check uninvited guests while building strings - handle potential empty lists or null elements:
Performance matters: Optimizing StringBuilder
Adding StringBuilder
capacity upfront is worth considering when dealing with larger datasets:
Guava's Joiner: The alternative approch
Need a tool with some extra muscle? Try Guava's Joiner:
Handle delimiter: It's not just about commas!
In handmade string builds, don't get tripped over by improper delimiter management:
Say Hi to i18n: Going global friendly
Remember to account for i18n when creating globally-conscious applications:
Don't reinvent the wheel
There's a reason for the existence of these great libraries - they are robust, widely tested, and optimized.
Was this article helpful?