Search code examples
javaguava

Join array and wrap every element with Guava Joiner


I have array of Strings for example:

String[] arr = {"one", "two", "three"};

Is possible with Guava Joiner get string like this:

"<one>, <two>, <three>"

where , is separator and < > are prefix and suffix for every element. Thanks.


Solution

  • Use a Joiner with the end of one and the start of the next:

    Joiner.on(">, <")
    

    And then just put a < on the start, and > on the end.

    "<" + Joiner.on(">, <").join(arr) + ">"
    

    You might want to handle the empty array case, to distinguish this from {""}:

    (arr.length > 0) ? ("<" + Joiner.on(">, <").join(arr) + ">") : ""