Java function for arrays like PHP's join()?
If you're looking for a quick solution, String.join()
is your friend. It's a simple and clean method to join array elements into a string, using any delimiter:
What's best, similar to PHP's join()
function, and ready for your service since Java 8.
Filling your toolbox
Apache Commons Lang StringUtils
While simplicity is gold, sometimes you need more power. Here is where StringUtils.join()
steps into the limelight:
Ze fancy Java 8 Style - Arrays.stream()
Java 8 ain't a two-trick pony. Combine Arrays.stream()
and Collectors.joining()
, and you get a stylish shortcut for string joining:
The classic way - StringBuilder
For those who prefer to do things manually and want full control, make use of StringBuilder
:
Stream API and StringJoiner - Level Up
If you're feeling adventurous and want some extra bamboozle, Stream API
and StringJoiner
are standing by:
Balance between performance and readability is the key while choosing your method.
Additional insights
Edge cases? Custom function to the rescue
There are times when you need to handle delimiter placement when going for a custom join function:
Android users, your friend - TextUtils.join()
Android developers, fear not! TextUtils.join()
has you covered:
Eager for custom solutions?
Custom logic is your mate for wide-ranging requirements. Roll out your own function:
Was this article helpful?