Join strings

This example will show how to concatenate strings while using java 8, guava and apache commons.

Java 8

The ability to combine strings in the core JDK arrived in Java 8 with String Joiner and String.join which allow for the ability to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. These methods syntactically are very similar to guava's joiner utility class. The snippets below will join Strings to produce the famous Green Bay Packer's Go Pack Go! chant.

StringJoiner

@Test
public void join_strings_java8_string_joiner() {

    StringJoiner joiner = new StringJoiner("-");

    String goPackGo = joiner.add("Go").add("pack").add("Go!").toString();

    assertEquals("Go-pack-Go!", goPackGo);
}

String.join

@Test
public void join_strings_java8_string_join() {

    String goPackGo = String.join("-", "Go", "pack", "Go!");

    assertEquals("Go-pack-Go!", goPackGo);
}

Google Guava

In this snippet will concatenate strings with separator using Guava's Joiner object which joins pieces of text with a separator.

@Test
public void join_strings_guava() {

    String goPackGo = Joiner.on("-").join("Go", "pack", "Go!");

    assertEquals("Go-pack-Go!", goPackGo);
}

Apache Commons

Using apache commons this snippet will join an ArrayList into a single string separated by a '-'.

@Test
public void join_strings_apache() {

    String goPackGo = StringUtils.join(Arrays.asList("Go", "pack", "Go!"),
            "-");

    assertEquals("Go-pack-Go!", goPackGo);
}