Join strings with hyphen

This example will show how to join multiple strings by a hyphen while using java 8, guava and apache commons. Java has many ways to combine strings and developers received some relief in java 8 with native support for joining strings. For example, you might have a database of zip codes in one column with the four digits in another. If your presentation wants to display in 52546-1234 you need to string those two values together with a dash. Let's have a look below. A similar example shows how to join strings with a separator as a comma.

Java 8

StringJoiner

@Test
public void join_strings_java8_string_joiner() {

    StringJoiner joiner = new StringJoiner("-");

    String stringsWithDash = joiner.add("53544").add("1234").toString();

    assertEquals("53544-1234", stringsWithDash);
}

String.join

@Test
public void join_strings_java8_string_join() {

    String stringsWithHyphen = String.join("-", "53544", "1234");

    assertEquals("53544-1234", stringsWithHyphen);
}

Google Guava

@Test
public void join_strings_guava() {

    String seperatedByDash = Joiner.on("-").join("53544", "1234");

    assertEquals("53544-1234", seperatedByDash);
}

Apache Commons

@Test
public void join_strings_apache() {

    String seperatedByHypen = StringUtils.join(
            Arrays.asList("53544", "1234"), "-");

    assertEquals("53544-1234", seperatedByHypen);
}