Sunday, June 23, 2019

Preferred Idiom for Joining a Collection of Strings in Java




Given a Collection of Strings, how would you join them in plain Java, without using an external Library?



Given these variables:



Collection data = Arrays.asList("Snap", "Crackle", "Pop");
String separator = ", ";
String joined; // let's create this, shall we?


This is how I'd do it in Guava:




joined = Joiner.on(separator).join(data);


And in Apache Commons / Lang:



joined = StringUtils.join(data, separator);


But in plain Java, is there really no better way than this?




StringBuilder sb = new StringBuilder();
for(String item : data){
if(sb.length()>0)sb.append(separator);
sb.append(item);
}
joined = sb.toString();

Answer



I'd say the best way of doing this (if by best you don't mean "most concise") without using Guava is using the technique Guava uses internally, which for your example would look something like this:




Iterator iter = data.iterator();
StringBuilder sb = new StringBuilder();
if (iter.hasNext()) {
sb.append(iter.next());
while (iter.hasNext()) {
sb.append(separator).append(iter.next());
}
}
String joined = sb.toString();



This doesn't have to do a boolean check while iterating and doesn't have to do any postprocessing of the string.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...