Java String join (CSV) example

SO far till java 7, we had String.split() method which can split a string based on some token passed as parameter. It returned list of string tokens as string array. But, if you want to join a string or create a CSV by concatenating string tokens using some separator between them, you have to iterate through list of Strings, or array of Strings, and then use StringBuilder or StringBuffer object to concatenate those string tokens and finally get the CSV.

String concatenation (CSV) with join()

Java 8 made the task easy. Now you have String.join() method where first parameter is separator and then you can pass either multiple strings or some instance of Iterable having instances of strings as second parameter. It will return the CSV in return.

package java8features;

import java.time.ZoneId;

public class StringJoinDemo {
public static void main(String[] args){
String joined = String.join("/","usr","local","bin");
System.out.println(joined);

String ids = String.join(", ", ZoneId.getAvailableZoneIds());
System.out.println(ids);
}
}

Output:

usr/local/bin
Asia/Aden, America/Cuiaba, Etc/GMT+9, Etc/GMT+8.....

So next time you use java 8 and want to concatanate the strings, you have a handy method in your kit. Use it.

Happy Learning !!

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial