Convert int[] to comma-separated string

后端 未结 6 733
情深已故
情深已故 2021-01-12 23:45

How can I convert int[] to comma-separated String in Java?

int[] intArray = {234, 808, 342};

Result I want:

\"         


        
6条回答
  •  -上瘾入骨i
    2021-01-13 00:05

    Here's a stream version which is functionally equivalent to khelwood's, yet uses different methods.

    They both create an IntStream, map each int to a String and join those with commas.

    They should be pretty identical in performance too, although technically I'm calling Integer.toString(int) directly whereas he's calling String.valueOf(int) which delegates to it. On the other hand I'm calling IntStream.of() which delegates to Arrays.stream(int[]), so it's a tie.

    String result = IntStream.of(intArray)
                             .mapToObj(Integer::toString)
                             .collect(Collectors.joining(", "));
    

提交回复
热议问题