Java:使用分隔符连接基元数组 [英] Java: join array of primitives with separator
问题描述
假设我有一个数组:
int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
我需要使用分隔符加入其元素,例如 -
,因此我应该得到这样的字符串:
And I need to join its elements using separator, for example, " - "
, so as the result I should get string like this:
"1 - 2 - 3 - 4 - 5 - 6 - 7"
我怎么能这样做?
PS:是的,我知道 this 和这个帖子,但它的解决方案不适用于基元数组。
PS: yes, I know about this and this posts, but its solutions won't work with an array of primitives.
推荐答案
这是我想出来的。有几种方法可以做到这一点,它们取决于你使用的工具。
Here what I came up with. There are several way to do this and they are depends on the tools you using.
使用 StringUtils
和 ArrayUtils
来自 Common Lang :
int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
String result = StringUtils.join(ArrayUtils.toObject(arr), " - ");
你不能只使用 StringUtils.join(arr, - );
因为 StringUtils
没有方法的重载版本。虽然,它有方法 StringUtils.join(int [],char)
。
You can't just use StringUtils.join(arr, " - ");
because StringUtils
doesn't have that overloaded version of method. Though, it has method StringUtils.join(int[], char)
.
适用于任何Java版本,从1.2。
Works at any Java version, from 1.2.
使用Java 8流:
东西像这样:
int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
String result = Arrays.stream(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining(" - "));
事实上,使用流来获得结果有很多变化。
In fact, there are lot of variations to achive the result using streams.
Java 8的方法 String.join()
仅适用于字符串,因此要使用它,你仍然需要转换 int []
to String []
。
Java 8's method String.join()
works only with strings, so to use it you still have to convert int[]
to String[]
.
String[] sarr = Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new);
String result = String.join(" - ", sarr);
如果你坚持使用Java 7或更早版本没有库,你可以编写自己的实用工具方法:
If you stuck using Java 7 or earlier with no libraries, you could write your own utility method:
public static String myJoin(int[] arr, String separator) {
if (null == arr || 0 == arr.length) return "";
StringBuilder sb = new StringBuilder(256);
sb.append(arr[0]);
//if (arr.length == 1) return sb.toString();
for (int i = 1; i < arr.length; i++) sb.append(separator).append(arr[i]);
return sb.toString();
}
比你可以做的:
int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
String result = myJoin(arr, " - ");
这篇关于Java:使用分隔符连接基元数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!