In Python it is pretty easy to display an iterable as comma separated list:
>>> iterable = ["a", "b", "c"]
>>> ", ".join(iterable)
'a, b, c'
Is there a Java way that comes close to this conciseness? (Notice that there is no "," at the end.)
Here are the versions using Guava and Commons / Lang that Michael referred to:
List<String> items = Arrays.asList("a","b","c");
// Using Guava
String guavaVersion = Joiner.on(", ").join(items);
// Using Commons / Lang
String commonsLangVersion = StringUtils.join(items, ", ");
// both versions produce equal output
assertEquals(guavaVersion, commonsLangVersion);
Reference:
Joiner.on(String)
Guava: Joiner.join(Iterable<T>)
Commons / Lang: StringUtils.join(Collection, String)
AbstractCollection.toString()
(which is inherited by pretty much all collections in the standard API) pretty much does that. For Arrays, you can use the Arrays.toString()
methods (which also work on primitive arrays).
There's probably something in Apache Commons Collections or Google Guava that allows you to choose the separator character and doesn't surround the results in brackets.
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