当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Guava Joiner doesn't have ability to prefix and suffix

问题描述:

This question already has an answer here:

  • Is there a way to join strings, each with a specific surrounding string?

    3 answers

网友答案:

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(","));
网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: