This question already has an answer here:
I have requirement in Joiner to have the ability to prefix and suffix elements.
For example
String str[] = {"a", "b", "c"};
Joiner.on(",").prefix("'").suffix("'").join(str);
Expected output would be:
'a','b','c'
Do we have any alternative for this? As Guava doesn't do it (or I'm not aware of). With java 8 is there a better alternative?
You can use Guava's
List#transform
to make the transformationa --> 'a'
and then useJoiner
on the transformed list.transform
only works onIterable
objects, though, not on arrays. The code will still be succinct enough:where the transformation is as follows:
One might say this is a long-winded way of doing this, but I admire the amount of flexibility provided by the
transform
paradigm.Edit (because now there's Java 8)
In Java 8, all this can be done in a single line using the Stream interface, as follows:
A more efficient solution is
which is also shorter than using a Function (at least without function literals; the handling of an empty input makes this solution ugly). The bad part is the fact that you have to include the prefix and suffix in the
Joiner
in an not really obvious way and repeat them. This example makes it more obvious:To get it right without thinking, just remember what comes out for
["+", "+"]
, namely[+], [+]
and use the plus-separated parts.