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 !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Java String join (CSV) example”

  1. Lokesh, I follow your posts regularly and they are really superb. Waiting for more JAVA 8 posts. Will you please do a post on Functions(Functional Programming).

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.