How to join list of string using delimiter in Java

1. Join list of strings using Java 8 String.join(…)

If we use Java 8, it is very easy to join a list or array of strings using a delimiter. For a common situation like building a CSV line, this approach is very easy and straightforward.

List<String> stringList = new ArrayList<>();
stringList.add("Name");
stringList.add("Sex");
stringList.add("eMail");
stringList.add("Phone");
stringList.add(null);

String line = String.join(", ", stringList);
System.out.println(line);


Output:
Name, Sex, eMail, Phone, null



The String.join(…) method accept Iterator. So we can use anything that is an Iterator. So we can use simply array of strings.

String [] dataList = new String[] {"John", "M", "john@johnsite.com",
    null, "Some notes"};
String line = String.join(", ", dataList);
System.out.println(line);


Output:
John, M, john@johnsite.com, null, Some notes



2. Join list of strings using Google Guava Joiner

Google Guava Joiner is a nice utility class which do the same job in more flexible way. Also there is no dependency on Java 8. On the earlier example, notice that the null values are being joined as ‘null’. Google guava Joiner has more control on null values. We can either choose to skip null values or replace null value with a string we desire.

First let us see how to skip null values:

Joiner joiner = Joiner.on(", ").skipNulls();
String line = joiner.join("Apple", "Guava", null, "Grape",
    "Lichi", "Banana");
System.out.println(line);


Output:
Apple, Guava, Grape, Lichi, Banana



And if we want to replace the null with some meaningful string, we can do:

String [] dataList = new String[] {"John", "M", "john@johnsite.com",
    null, "Some notes"};
Joiner joiner = Joiner.on(", ").useForNull("Unknown");
String line = joiner.join(dataList);
System.out.println(line);


Output:
John, M, john@johnsite.com, Unknown, Some notes


Note: We can use just

Joiner joiner = Joiner.on(", ");

In this case if there is any null value in the list, a NullReferenceException will be thrown.



References:


Download source



Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus