EN
Java - convert Array to comma separated String
1
answers
3
points
Is there easier way to convert Array of Strings to comma separated String in java?
I guess maybe it is possible using streams and java 8?
My current code works, but it's kind of long and messy..
public class JoinerExample {
public static void main(String[] args) {
String[] users = {"Ann", "John", "Kate"};
StringBuilder builder = new StringBuilder();
for (int i = 0; i < users.length; i++) {
builder.append(users[i]);
if (i != users.length - 1) {
builder.append(",");
}
}
String joined = builder.toString();
System.out.println(joined); // Ann,John,Kate
}
}
Output:
Ann,John,Kate
1 answer
2
points
It is very easy way to join a Array or List of String with commas.
Quick solution with java 8 String.join method:
// Java 8
String.join(",", users);
If we don't have java 8, we can use Guava Joiner, quick example:
// Guava Joiner
Joiner.on(",").join(users)
1. Java 8 - String.join
public class StringJoinerExample {
public static void main(String[] args) {
String[] users = {"Ann", "John", "Kate"};
String join = String.join(",", users);
System.out.println(join); // Ann,John,Kate
}
}
Output:
Ann,John,Kate
2. Java 8 - Arrays.stream + Collectors.joining
import java.util.Arrays;
import java.util.stream.Collectors;
public class CollectorsExample {
public static void main(String[] args) {
String[] users = {"Ann", "John", "Kate"};
String join = Arrays.stream(users)
.collect(Collectors.joining(","));
System.out.println(join); // Ann,John,Kate
}
}
Output:
Ann,John,Kate
3. Guava Joiner
import com.google.common.base.Joiner;
public class JoinerExample {
public static void main(String[] args) {
String[] users = {"Ann", "John", "Kate"};
String join = Joiner.on(",").join(users);
System.out.println(join); // Ann,John,Kate
}
}
Ann,John,Kate
4. Old school for loop and StringBuilder
It is the way in the question. We can use just old school for loop and StringBuilder.
0 comments
Add comment