Given a Collection of Strings, how would you join them in plain Java, without using an external Library?
Given these variables:
Collection
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();
In Java 8:
String.join (separator, data)
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.
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();
Collectors can join Streams which is very useful if you want to filter
or map
your data.
String joined = Stream.of("Snap", "Crackle", "Pop")
.map(String::toUpperCase)
.collect(Collectors.joining(", "));
To get a Stream from a Collection, call stream() on it:
Arrays.asList("Snap", "Crackle", "Pop").stream()
Different intentions:
For third-part tools, such as Guava's Joiner
, which is not fast, but very flexible. There are many option methods to customize join behavior, such as skipNulls()
.
Plain Java is fast, but it needs you write some lines of codes by yourself.