Split string by comma

Let's say you have a comma delimited file or a phrase that you want to divide each element on all the commas. This example will show how to parse a string on a comma using java, guava and apache commons. A similar example shows how to parse comma delimited string in groovy.

Straight up Java

Using java's core String.split function we will pass a regular expression that will return an array of strings computed by splitting the original on a comma.

@Test
public void split_string_comma_java() {

    String[] elementsInString = "Yo,Gabba, Gabba, Keep Trying".split(",");

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

    assertTrue(elementsInString.length == 4);
}

Java 8

Creating a stream from a string then applying the java 8 function to the elements will produce an Arraylist of String arrays. Calling the flatmap will replace or combine each array into a single stream by flattening it. Finally we will convert stream into arraylist.

@Test
public void split_string_comma_java8() {

    List<String> splitByComma = Stream.of("Yo,Gabba, Gabba, Keep Trying")
            .map(w -> w.split(",")).flatMap(Arrays::stream)
            .collect(Collectors.toList());

    logger.info(splitByComma);

    assertTrue(splitByComma.size() == 4);
}

Google Guava

Using guava's Splitter class 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_comma_guava() {

    List<String> elementsInString = Splitter.on(",").splitToList(
            "Yo,Gabba, Gabba, Keep Trying");

    logger.info(elementsInString);

    assertEquals(4, elementsInString.size());

}

Apache Commons

This snippet will split text into an array using a comma as a separator using apache commons StringUtils.split.

@Test
public void split_string_white_space_using_apache_commons() {

    String[] elementsInString = StringUtils.split(
            "Yo,Gabba, Gabba, Keep Trying", ",");

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

    assertTrue(elementsInString.length == 4);
}