Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 434
deamon Avatar asked Nov 08 '10 09:11

deamon


2 Answers

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)

like image 118
Sean Patrick Floyd Avatar answered Nov 12 '22 20:11

Sean Patrick Floyd


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.

like image 32
Michael Borgwardt Avatar answered Nov 12 '22 20:11

Michael Borgwardt