Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

By hand

Back in the olden days, if you needed a CSV, you would create it by iterating over your data, appending to a String with your separator, then lopping off the last character. Something like this:

StringBuilder messages = new StringBuilder();   
for (String message : kycModel.getMessages()) { 


Along came Apache Commons and we started using StringUtils.join.

myObject.setValue(StringUtils.join(messages, ","));

Java 8 StringJoiner

Java 8 brought the StringJoiner. The StringJoiner constructor comes in 2 flavors.
new StringJoiner(delimiter)

  • delimeter – the value that will be used to separate the items. The “,” is used for a CSV.

new StringJoiner(delimeter, prefix, suffix)

  • delimeter – The delimeter is the same as the regular constructor.
  • prefix – a character(s) that will be put at the beginning of the sequence (e.g. “[“).
  • suffix – the character(s) that will be placed at the end of the sequence (e.g. “]”).

An example of using the StringJoiner:

StringJoiner stringJoiner = new StringJoiner(",");  
for (String message : kycModel.getMessages()) {     

That can be made much easier by using the Java 8 forEach:

StringJoiner stringJoiner = new StringJoiner(",");

If you really want to squeeze it down further, you can also take advantage of the Java 8 stream


September 15th, 2015

Posted In: Java, java ninja, Javaninja, Stream

Tags: , , , , ,

Leave a Comment

WP to LinkedIn Auto Publish Powered By :