将int []转换为逗号分隔的字符串 [英] Convert int[] to comma-separated string

查看:130
本文介绍了将int []转换为逗号分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中将int[]转换为逗号分隔的字符串?

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

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

我想要的结果:

"234, 808, 342"

这里有非常相似的参考问题,但我需要的这些解决方案均未提供结果.

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

如何打印Java对象而不获取"SomeType @ 2f92e0f4"?

如何转换List< String>成逗号分隔的字符串,而无需显式迭代List

到目前为止我已经尝试过的

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

推荐答案

这是一个流版本,在功能上与khelwood相同,但是使用了不同的方法.

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

它们都创建一个IntStream,将每个int映射到一个String,并用逗号将它们连在一起.

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

它们的性能也应该完全相同,尽管从技术上来说我直接叫Integer.toString(int),而他叫的是委托给它的String.valueOf(int).另一方面,我正在呼叫IntStream.of(),后者将委托给Arrays.stream(int[]),所以这是平局.

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

这篇关于将int []转换为逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆