Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - 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.

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(", "));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...