0

There are lots of questions about how to join a String[] in Java 8 with a delimiter, but how should a String[] be joined without a delimiter?

For example, {"a", "b", "c"} becomes "abc".


Note: I know how to write a small function for this myself, so please do not leave custom solutions. I am looking for a one-liner from the standard library.

Community
  • 1
  • 1
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245

2 Answers2

6
public class Test {
    public static void main(String[] args) {
        System.out.println( String.join("", new String[]{"a", "b", "c"}) );
}}

Outputs: abc

The relevant part being String.join("", arrayStrings);

Javadoc for String.join

Loduwijk
  • 1,950
  • 1
  • 16
  • 28
  • 4
    Now that I think about it, I could have just used args as the string array... whatever. – Loduwijk Feb 09 '17 at 15:12
  • Sure, let's edit it like that and see what the moderators think about it. :) – Per Lundberg Nov 16 '18 at 11:19
  • @PerLundberg I don't quite understand the comment: "See what the moderators think about it"? _Also_, per the edit, I used `new String[]{"a", "b", "c"}` to be explicit: to be clear from the example about what exactly was joined, and then I show the output below that would be achieved from it. Is the `new String[]{...}` syntax detracting from the answer? – Loduwijk Nov 19 '18 at 15:04
  • I was referring to the fact that edits are peer-moderated if you have less than 2000 reputation. The edit I suggested was rejected, which is fine; it's actually a bit clearer like you have it right now. A colleague of mine suggested another approach today so I added this a separate answer for clarity (don't really want to post code samples as a comment) – Per Lundberg Nov 19 '18 at 21:44
  • @PerLundberg Oh! I think I understand now. I did not even notice my own comment that I left way back when, and it appears that you were responding to that. Sorry. In fact, now I wonder why I thought using `args` would have been advantageous, as that would only have made it less obvious what was happening. Anyway, I see now where you're coming from. – Loduwijk Nov 19 '18 at 22:42
1

Adding to what has already been said, you can even do it as simple as this if you so prefer:

public class Test {
    public static void main(String[] args) {
        System.out.println(String.join("", "a", "b", "c"));
    }
}

I.e. you don't even have to wrap it in an array; since String.join takes a ... (variable argument), you can just specify any number of String arguments without explicitly wrapping them in an String[] object.


Note: the big disadvantage of the approach above is that it obscures the distinction between the delimiter and the delimited strings; @Aaron's answer is generally preferable. But anyhow, it deserves to be mentioned that you can actually write it like this also.

Per Lundberg
  • 3,837
  • 1
  • 36
  • 46