Given a Collection of Strings, how would you join them in plain Java, without using an external Library?
Given these variables:
Collection<String> 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();
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<String> 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.
May be instead of calling sb.length() again and again in a loop, i have slightly modified.
StringBuilder sb = new StringBuilder();
String separator = "";
for(String item : data){
sb.append(separator);
separator=",";
sb.append(item);
}
joined = sb.toString();
joined =
String.join(separator, data);
StringBuilder sb = new StringBuilder();
boolean first = true;
for(String item : data){
if(!first || (first = false)) sb.append(separator);
sb.append(item);
}
joined = sb.toString();
In Java 8:
String.join (separator, data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With