Split string by colon

If you by passed parsing json with a library and you have a string separated that was provided to you by a vendor, the snippets below will show you how to separate the string in a collection. A colon is a punctuation mark (:) indicating. This example follows similar approach found in parse string on comma.

Straight up Java

Using java's String.split method passing a regex will return an array of strings computed by splitting the original on a colon.

@Test
public void split_string_colon_java() {

    String[] colonArray = "This:is:a:sentence:by:colon".split(":");

    logger.info(Arrays.toString(colonArray));

    assertTrue(colonArray.length == 6);
}

Java 8

Producing a stream of strings then applying a java 8 function to the elements will produce an Arraylist of String arrays. Calling the flatmap will combine each array into a single stream by flattening it. Finally we will transform stream into arraylist.

@Test
public void split_string_colon_java8() {

    List<String> splitByColon = Stream.of("This:is:a:sentence:by:colon")
            .map(w -> w.split(":")).flatMap(Arrays::stream)
            .collect(Collectors.toList());

    logger.info(splitByColon);

    assertTrue(splitByColon.size() == 6);
}

Google Guava

Using guava's splitter we will parse a comma delimited string by passing a comma as a separator to the on method. Next we will call the splitToList function that will split the sequence into chunks and make them available via an ArrayList.

@Test
public void split_string_colon_guava() {

    List<String> elementsInString = Splitter.on(":").splitToList(
            "This:is:a:sentence:by:colon");

    logger.info(elementsInString);

    assertEquals(6, elementsInString.size());

}

Apache Commons

Splits the provided text into an array, separators specified. This is an alternative to using StringTokenizer.

@Test
public void split_string_colon_using_apache_commons() {

    String[] elementsInString = StringUtils.split(
            "This:is:a:sentence:by:colon", ":");

    logger.info(Arrays.toString(elementsInString));

    assertTrue(elementsInString.length == 6);
}