Join strings with comma

This example will show how to join multiple strings by a comma while using java 8, guava and apache commons. An opposite example shows how to splitting a comma separated string.

Java 8

StringJoiner

@Test
public void join_strings_java8_string_joiner() {

    StringJoiner joiner = new StringJoiner(",");

    String stringsWithCommas = joiner.add("Design").add("a")
            .add("T-shirt!").toString();

    assertEquals("Design,a,T-shirt!", stringsWithCommas);
}

String.join

@Test
public void join_strings_java8_string_join() {

    String commaSeperated = String.join(",", "Design", "a", "T-shirt!");

    assertEquals("Design,a,T-shirt!", commaSeperated);
}

Google Guava

@Test
public void join_strings_guava() {

    String commaSeperatedString = Joiner.on(",").join("Design", "a",
            "T-shirt!");

    assertEquals("Design,a,T-shirt!", commaSeperatedString);
}

Apache Commons

@Test
public void join_strings_apache() {

    String separatedByCommas = StringUtils.join(
            Arrays.asList("Design", "a", "T-shirt!"), ",");

    assertEquals("Design,a,T-shirt!", separatedByCommas);
}