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()) { 
    messages.append(message).append(",");       
}                                               
myObject.setValue(messages.toString());                        

Apache

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()) {     
    stringJoiner.add(message);                      
}                                                   
myObject.setValue(stringJoiner.toString());         

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

StringJoiner stringJoiner = new StringJoiner(",");
kycModel.getMessages().forEach(stringJoiner::add);
myObject.setValue(stringJoiner.toString());

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

myObject.setValue(kycModel.getMessages().stream().map(String::toString).collect(Collectors.joining(",")));  

September 15th, 2015

Posted In: Java, java ninja, Javaninja, Stream

Tags: , , , , ,

Leave a Comment

LinkedIn Auto Publish Powered By : XYZScripts.com