While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be i
If you're using Eclipse Collections, you can use makeString()
or appendString()
.
makeString()
returns a String
representation, similar to toString()
.
It has three forms
makeString(start, separator, end)
makeString(separator)
defaults start and end to empty stringsmakeString()
defaults the separator to ", "
(comma and space)Code example:
MutableList list = FastList.newListWith(1, 2, 3);
assertEquals("[1/2/3]", list.makeString("[", "/", "]"));
assertEquals("1/2/3", list.makeString("/"));
assertEquals("1, 2, 3", list.makeString());
assertEquals(list.toString(), list.makeString("[", ", ", "]"));
appendString()
is similar to makeString()
, but it appends to an Appendable
(like StringBuilder
) and is void
. It has the same three forms, with an additional first argument, the Appendable.
MutableList list = FastList.newListWith(1, 2, 3);
Appendable appendable = new StringBuilder();
list.appendString(appendable, "[", "/", "]");
assertEquals("[1/2/3]", appendable.toString());
If you can't convert your collection to an Eclipse Collections type, just adapt it with the relevant adapter.
List
Note: I am a committer for Eclipse collections.