Guava Joiner doesn't have ability to prefix an

2019-04-27 07:10发布

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?

2条回答
劳资没心,怎么记你
2楼-- · 2019-04-27 07:23

You can use Guava's List#transform to make the transformation a --> 'a' and then use Joiner on the transformed list. transform only works on Iterable objects, though, not on arrays. The code will still be succinct enough:

List<String> strList = Lists.newArraylist(str); // where str is your String[]
Joiner.on(',').join(Lists.transform(str, surroundWithSingleQuotes));

where the transformation is as follows:

Function<String, String> surroundWithSingleQuotes = new Function<String, String>() {
    public String apply(String string) {
        return "'" + string + "'";
    }
};

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:

strList.stream().map(s -> "'" + s + "'").collect(Collectors.joining(","));
查看更多
冷血范
3楼-- · 2019-04-27 07:34

A more efficient solution is

String str[] = {"a", "b", "c"}; // or whatever
if (str.length == 0 ) {
    return "";
}
return "'" + Joiner.on("','").join(str) + "'";

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:

return "[" + Joiner.on("], [").join(str) + "]";

To get it right without thinking, just remember what comes out for ["+", "+"], namely [+], [+] and use the plus-separated parts.

查看更多
登录 后发表回答