Explain Codes LogoExplain Codes Logo

A quick and easy way to join array elements with a separator (the opposite of split) in Java

java
string-joining
utility-tools
best-practices
Anton ShumikhinbyAnton Shumikhin·Aug 10, 2024
TLDR

The quickest way in Java to join array elements with a separator is using Java 8's String.join():

String result = String.join(", ", "One", "Two", "Three"); // You get: "One, Two, Three"

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:

String[] array = {"Java", "Python", "C++"}; String joined = String.join(" | ", array); // Forget fight club, let's have a language club :)

And a list:

List<String> list = Arrays.asList("Java", "Python", "C++"); String joined = String.join(" / ", list); // Language Unity, yay!

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:

public static String joinWithSeparator(String[] array, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; i++){ sb.append(array[i]); if (i < array.length - 1) { // No extra, trailing separators. Nuh-uh. sb.append(separator); } } return sb.toString(); }

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:

String joined = TextUtils.join(" + ", new String[]{"Android", "iOS", "Windows"}); // Forms the Developer Trinity, sweet!

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:

Joiner joiner = Joiner.on("; ").skipNulls(); String result = joiner.join("Java", null, "Scala", "Kotlin"); // Null was here, but got bravely skipped. Some call it the Joiner Magic! 🎩💫

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:

String result = StringUtils.join(new String[]{"Sun", "Moon", "Venus"}, ", "); // Here, we are literally joining celestial bodies! 🌌

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:

Map<String, String> map = new HashMap<>(); map.put("Key1", "Value1"); map.put("Key2", "Value2"); String mapAsString = Joiner.on(", ").withKeyValueSeparator(" -> ").join(map); // Map says, "United we stand, joined we shine!" 🗝️->💡