In Java, you can join strings with StringJoiner, String's join method, StringBuilder, StringBuffer, String's concat method and + operator
Using Java 8+ StringJoiner
StringJoiner is used to join a sequence of strings by a delimiter
@Test
public void joinWithStringJoiners() {
StringJoiner stringJoiner = new StringJoiner(", ");
stringJoiner.add("apple")
.add("orange")
.add("passion");
String result = stringJoiner.toString();
assertThat(result).isEqualTo("apple, orange, passion");
}
Using Java 8+ String's join method
String's join method is used to join an array or any Iterable collections like List or Set of strings by a delimiter
@Test
public void joinArrayOfStringsWithStringJoin() {
String[] arr = {"apple", "orange", "passion"};
String result = String.join(", ", arr);
assertThat(result).isEqualTo("apple, orange, passion");
}
@Test
public void joinListOfStringsWithStringJoin() {
List<String> lst = Arrays.asList("apple", "orange", "passion");
String result = String.join(", ", lst);
assertThat(result).isEqualTo("apple, orange, passion");
}
@Test
public void joinSetOfStringsWithStringJoin() {
Set<String> set = new LinkedHashSet<>(Arrays.asList("apple", "orange", "passion"));
String result = String.join(", ", set);
assertThat(result).isEqualTo("apple, orange, passion");
}
Using StringBuilder, StringBuffer, String's concat method or + operator
StringBuilder, StringBuffer, String's concat method and + operator do not support delimiter, we have to handle manually
@Test
public void joinStringsWithStringConcat() {
String joinedString = "apple"
.concat(",")
.concat("orange")
.concat(";")
.concat("passion");
assertThat(joinedString).isEqualTo("apple, orange; passion");
}
Conclusion
In this tutorial, we learned various methods to join strings in Java. While StringJoiner and String's join methods support to join strings with delimiter, other methods offer more flexible. You can find the full source code as below