Explain Codes LogoExplain Codes Logo

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

java
functions
performance
best-practices
Alex KataevbyAlex Kataev·Oct 18, 2024
TLDR

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:

String result = String.join("-", "Java", "is", "fun"); // result is "Java-is-fun"

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:

String[] words = {"Java", "is", "thrilling"}; String joinedStrings = StringUtils.join(words, "--"); // Joined string: "Java--is--thrilling"

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:

String[] words = {"Java", "8", "Rocks"}; String result = Arrays.stream(words).collect(Collectors.joining("!!")); // Cheers: "Java!!8!!Rocks"

The classic way - StringBuilder

For those who prefer to do things manually and want full control, make use of StringBuilder:

StringBuilder sb = new StringBuilder(); for (String s : array) { if (sb.length() > 0) { sb.append(","); // Adding Ye olde separator } sb.append(s); } // Voila...you have your joined string

Stream API and StringJoiner - Level Up

If you're feeling adventurous and want some extra bamboozle, Stream API and StringJoiner are standing by:

StringJoiner sj = new StringJoiner("!!"); for (String s : array) { sj.add(s); } // Wooho...you get your joined string with '!!'

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:

public static String customJoin(String[] array, String separator) { StringBuilder result = new StringBuilder(); for (int i = 0; i < array.length; i++) { result.append(array[i]); if (i < array.length - 1) result.append(separator); // Watch out for this edge case } return result.toString(); }

Android users, your friend - TextUtils.join()

Android developers, fear not! TextUtils.join() has you covered:

String[] words = {"Android", "is", "cool"}; String joinedWords = TextUtils.join(" ", words); // joinedWords is "Android is cool", yup cool, just like you 😎

Eager for custom solutions?

Custom logic is your mate for wide-ranging requirements. Roll out your own function:

// Here's one handling nulls and empty strings for you public static String customFilteredJoin(String[] array, String delimiter) { return Arrays.stream(array) .filter(s -> s != null && !s.isEmpty()) // Filtering out unwanted nulls and empties .collect(Collectors.joining(delimiter)); }