A quick and easy way to join array elements with a separator (the opposite of split) in Java
The quickest way in Java to join array elements with a separator is using Java 8's String.join()
:
Utilizing String.join()
for different data types
Effortless joining for arrays and lists
String.join()
can effortlessly join the elements from both arrays and lists. Here's it in action with an array:
And a list:
Creating a tailored join utility
If you prefer not being tied to external dependencies, a custom join utility using StringBuilder
is the way to go:
This joinWithSeparator
function allows us to deal with trailing separators and custom iteration control, in essence, boss-level string joining.
Making use of various utility tools
Cruising through Android with TextUtils.join
In Android development, TextUtils.join
is your trusty sidekick. It functions like String.join()
and runs smoothly with the Android API:
Snow White's apple: Joiner
from Guava
Guava equips you with Joiner
for slick string joining, and it comes with the ability to handle null
values in style:
Apache's secret weapon: StringUtils.join
Another secret weapon from the Apache Commons Lang arsenal is StringUtils.join()
, a fantastic tool for transforming arrays into a string with your chosen separator:
Joining map entries efficiently with Joiner
Let's say you have to concatenate map entries. Joiner
from Guava allows you to do it in an optimum manner:
Was this article helpful?