0

Is there an elegant way (elegant meaning without an iterator or a loop) to print every member of Java's List<Sting> object into a comma-separated string?

E.g., Java's version of Perl's my $allElementsString = join(",", @myStrings);

I checked List interface and didn't find anything promising (my best guess was to use toArray and then Array's toString?)

DVK
  • 126,886
  • 32
  • 213
  • 327
  • 2
    `List.toString()` would return a comma-separated list, but it would include braces on the end. – Louis Wasserman Oct 08 '13 at 16:30
  • @zch - probably a closer one is http://stackoverflow.com/questions/63150/whats-the-best-way-to-build-a-string-of-delimited-items-in-java – DVK Oct 08 '13 at 16:37

9 Answers9

4

There's nothing in the JDK to do this directly. You can implement your own joiner with StringBuilder or use a 3rd party library like Guava

List<String> string = ...;
String list = Joiner.on(",").join(string);
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

if it is a list of Strings then simply print it :

System.out.println(yourList);

If it is a list of custom objects then make sure you have overriden toString method in your custom class to print the List objects properly.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

I think most people use Apache Commons' StringUtils:

List<String> yourStrings = /* something */;
String commaSeperated = StringUtils.join(yourStrings, ',');

The Apache Commons libraries are extremely convenient. I'd recommend looking at them (or Google's Guava).

Brendan Long
  • 53,280
  • 21
  • 146
  • 188
1

Something like this:

List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
String result = list.toString().substring(1, list.toString().length() - 1);
System.out.println(result);

OUTPUT:

1, 2, 3
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • Writing it as a one-liner does not pay off calling `list.toString()` twice, especially in real-life code where the list might be large. Having one more line of code for a local variable is not that bad. – Holger Oct 08 '13 at 17:26
0

Not in the JDK but there is guava and other utility libraries also offer similar solutions.

Pyranja
  • 3,529
  • 22
  • 24
0

Nope. Any toString method you might apply to List or the Array wouldn't be formatted in any meaningful way.

Kyle Falconer
  • 8,302
  • 6
  • 48
  • 68
0

Either use Guava as already pointed out, or Apache Common's StringUtils:

StringUtils.join( list, ",");
Thomas
  • 87,414
  • 12
  • 119
  • 157
0

See Best way to concatenate List of String objects?

Quoted, Use one of the the StringUtils.join methods in Apache Commons Lang.

import org.apache.commons.lang3.StringUtils;

String result = StringUtils.join(list, ", ");
Community
  • 1
  • 1
ChuckCottrill
  • 4,360
  • 2
  • 24
  • 42
0

you can use org.apache.commons.lang.StringUtils.join method

stinepike
  • 54,068
  • 14
  • 92
  • 112