Java: function for arrays like PHP's join()?


Question

I want to join a String[] with a glue string. Is there a function for this?

1
254
10/4/2009 2:52:01 AM

Accepted Answer

Starting from Java8 it is possible to use String.join().

String.join(", ", new String[]{"Hello", "World", "!"})

Generates:

Hello, World, !

Otherwise, Apache Commons Lang has a StringUtils class which has a join function which will join arrays together to make a String.

For example:

StringUtils.join(new String[] {"Hello", "World", "!"}, ", ")

Generates the following String:

Hello, World, !
307
8/26/2017 9:04:38 PM

If you were looking for what to use in android, it is:

String android.text.TextUtils.join(CharSequence delimiter, Object[] tokens)

for example:

String joined = TextUtils.join(";", MyStringArray);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon