Displaying list in Java as elegant as in Python
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:
- Guava:
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.
精彩评论