Java:用分隔符连接原语数组 [英] Java: join array of primitives with separator

查看:47
本文介绍了Java:用分隔符连接原语数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设,我有一个数组:

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: 是的,我知道 thisthis 帖子,但它的解决方案不适用于原始数组.

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.

使用来自 StringUtilsArrayUtils普通语言:

Using StringUtils and ArrayUtils from 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 流:

Using Java 8 streams:

像这样:

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[] 转换为 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屋!

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