Concatenating elements in an array to a string

前端 未结 19 2276
慢半拍i
慢半拍i 2020-12-08 02:43

I\'m confused a bit. I couldn\'t find the answer anywhere ;(

I\'ve got an String array:

String[] arr = [\"1\", \"2\", \"3\"];

then

19条回答
  •  攒了一身酷
    2020-12-08 03:12

    Using Guava's Joiner (which in r18 internally uses StringBuilder)

    String[]  arr= {"1","2","3"};
    Joiner noSpaceJoiner = Joiner.on("");
    noSpaceJoiner.join(arr))
    

    Joiner is useful because it is thread-safe and immutable and can be reused in many places without having to duplicate code. In my opinion it also is more readable.


    Using Java 8's Stream support, we can also reduce this down to a one-liner.

    String concat = Stream.of(arr).collect(Collectors.joining());
    

    Both outputs in this case are 123

提交回复
热议问题