9

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

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

Result I want:

"234, 808, 342"

Here are very similar reference question but none of those solution provide a result, exact I need.

What I've tried so far,

String commaSeparatedUserIds = Arrays.toString(intArray); // result: "[234, 808, 342]"
String commaSeparatedUserIds = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", ""); // result: "234808342"
String commaSeparatedUserIds = intArray.toString();  // garbage result
Biffen
  • 6,249
  • 6
  • 28
  • 36
Krunal
  • 77,632
  • 48
  • 245
  • 261

5 Answers5

15

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(", "));
Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • This works but creates potentially a lot of intermediate `String` objects, if the array is long. I'll add an answer for the fast (old-school) way of doing it. – Luke Hutchison Oct 24 '20 at 22:48
13

This should do

String arrAsStr = Arrays.toString(intArray).replaceAll("\\[|\\]", "");

After Arrays toString, replacing the [] gives you the desired output.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
6
        int[] intArray = {234, 808, 342, 564};
        String s = Arrays.toString(intArray);
        s = s.substring(1,s.length()-1);

This should work. basic idea is to get sub string from Arrays.toString() excluding first and last character

If want quotation in result, replace last line with:

s = "\"" + s.substring(1,s.length()-1) + "\"";
Bikas Katwal
  • 1,895
  • 1
  • 21
  • 42
5

You want to convert the ints to strings, and join them with commas. You can do this with streams.

int[] intArray = {234, 808, 342};
String s = Arrays.stream(intArray)
                 .mapToObj(String::valueOf) // convert each int to a string
                 .collect(Collectors.joining(", ")); // join them with ", "

Result:

"234, 808, 342"
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • I've tried your solution and editor showing warning to `Set project compiler compliance settings to 1.8` and `Set project JRE build path entry to 'JavaSE-1.8'`. While I have already set `JRE System Library [Java SE 1.8]` for `Java Build Path` for my project – Krunal Mar 08 '18 at 12:31
  • @Krunal Check for your compiler version too ? – Suresh Atta Mar 08 '18 at 12:33
2

This is the pattern I always use for separator-joining. It's a pain to write this boilerplate every time, but it's much more efficient (in terms of both memory and processing time) than the newfangled Stream solutions that others have posted.

public static String toString(int[] arr) {
    StringBuilder buf = new StringBuilder();
    for (int i = 0, n = arr.length; i < n; i++) {
        if (i > 0) {
            buf.append(", ");
        }
        buf.append(arr[i]);
    }
    return buf.toString();
}
Luke Hutchison
  • 8,186
  • 2
  • 45
  • 40
  • @Kayaman obviously it's longer than your version, and also obviously, most of the time performance doesn't matter much. But if you're dealing with files gigabytes in size (which I routinely do), you need something dramatically less wasteful on resources than your solution -- which is why I provided this as an alternative. You don't believe me about how much faster my solution is than yours? Benchmark it. I have benchmarked similar things many times before, and I was horrified at how much performance I was losing through using the new stream API and the lambda system. – Luke Hutchison Jun 19 '22 at 18:28
  • This is not low-level performance stuff. We're talking about an order of magnitude of difference in performance. As I said I have benchmarked this several times. I don't have the time or the motivation to do that again just to prove the point to you. – Luke Hutchison Jun 20 '22 at 20:39