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 );
}
Join strings with comma posted by Justin Musgrove on 17 June 2015
Tagged: java and java-string
Share on: Facebook Google+
All the code on this page is available on github:
JoinStringsComma.java