Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int[] to comma-separated string

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.

  • How to convert an int array to String with toString method in Java

  • How do I print my Java object without getting "SomeType@2f92e0f4"?

  • How to convert a List<String> into a comma separated string without iterating List explicitly

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
like image 528
Krunal Avatar asked Mar 08 '18 12:03

Krunal


People also ask

How to convert int array to comma-separated string in c#?

We can convert an array of integers to a comma-separated string by using the String. split() method in C#.

How to convert string with comma into number in JavaScript?

We can parse a number string with commas thousand separators into a number by removing the commas, and then use the + operator to do the conversion. We call replace with /,/g to match all commas and replace them all with empty strings.


2 Answers

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(", "));
like image 172
Kayaman Avatar answered Sep 29 '22 05:09

Kayaman


This should do

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

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

like image 43
Suresh Atta Avatar answered Sep 29 '22 05:09

Suresh Atta