Java:用分隔符连接原语数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38425623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:19:51  来源:igfitidea点击:

Java: join array of primitives with separator

javaarraysjoinseparator

提问by spirit

Suppose, I have an array:

假设,我有一个数组:

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"

How could I do this?

我怎么能这样做?

PS:yes, I know about thisand thisposts, but its solutions won't work with an array of primitives.

PS:是的,我知道这个这个帖子,但它的解决方案不适用于一系列原语。

采纳答案by spirit

Here what I came up with. There are several way to do this and they are depends on the tools you using.

这是我想出的。有几种方法可以做到这一点,它们取决于您使用的工具。



Using StringUtilsand ArrayUtilsfrom Common Lang:

使用StringUtilsArrayUtils来自Common Lang

int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
String result = StringUtils.join(ArrayUtils.toObject(arr), " - ");

You can't just use StringUtils.join(arr, " - ");because StringUtilsdoesn't have that overloaded version of method. Though, it has method StringUtils.join(int[], char).

您不能仅仅使用,StringUtils.join(arr, " - ");因为StringUtils没有方法的重载版本。虽然,它有方法StringUtils.join(int[], char)

Works at any Java version, from 1.2.

适用于任何 Java 版本,从 1.2 开始。



Using Java 8 streams:

使用 Java 8 流:

Something like this:

像这样的东西:

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's method String.join()works only with strings, so to use it you still have to convert int[]to String[].

Java的8的方法String.join()仅适用于字符串,所以使用它,你还是要转换int[]String[]

String[] sarr = Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new);
String result = String.join(" - ", sarr);


If you stuck using Java 7 or earlier with no libraries, you could write your own utility method:

如果您坚持使用没有库的 Java 7 或更早版本,您可以编写自己的实用程序方法:

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();
}

Than you can do:

比你能做的:

int[] arr = new int[] {1, 2, 3, 4, 5, 6, 7};
String result = myJoin(arr, " - ");

回答by RMachnik

You can use Guava for joining elements. More examples and docs you can find there. https://github.com/google/guava/wiki/StringsExplained

您可以使用 Guava 来连接元素。您可以在那里找到更多示例和文档。https://github.com/google/guava/wiki/StringsExplained

Joiner.on("-")
      .join(texts);

To be more precise you should firstly wrap your array into a Listwith Arrays.asList()or Guava's primitive-friendlyequivalents.

更准确地说,您应该首先将数组包装成ListwithArrays.asList()或 Guava 的原始友好等价物。

Joiner.on("-")
      .join(Arrays.asList(1, 2, 3, 4, 5, 6, 7));

Joiner.on("-")
      .join(Ints.asList(arr));

回答by Elliott Frisch

In Java 8+ you could use an IntStreamand a StringJoiner. Something like,

在 Java 8+ 中,您可以使用 anIntStream和 a StringJoiner。就像是,

int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7 };
StringJoiner sj = new StringJoiner(" - ");
IntStream.of(arr).forEach(x -> sj.add(String.valueOf(x)));
System.out.println(sj.toString());

Output is (as requested)

输出是(根据要求)

1 - 2 - 3 - 4 - 5 - 6 - 7

回答by engAnt

I'm sure there's a way to do this in Kotlin/Scala or other JVM languages as well but you could always stick to keeping things simple for a small set of values like you have above:

我确信在 Kotlin/Scala 或其他 JVM 语言中也有一种方法可以做到这一点,但您可以始终坚持对一小组值保持简单,就像上面那样:

int i, arrLen = arr.length;
 StringBuilder tmp = new StringBuilder();
 for (i=0; i<arrLen-1; i++)
    tmp.append(arr[i] +" - ");
 tmp.append(arr[arrLen-1]);

 System.out.println( tmp.toString() );

回答by Lin W

int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7 };

IntStream.of(arr).mapToObj(i -> String.valueOf(i)).collect(Collectors.joining(",")) ;

回答by bourne2program

I've been looking for a way to join primitives in a Stream without first instantiating strings for each one of them. I've come to this but it still requires boxing them.

我一直在寻找一种在 Stream 中加入原语的方法,而无需先为每个原语实例化字符串。我已经到了这个,但它仍然需要拳击他们。

LongStream.range(0, 500).boxed().collect(Collector.of(StringBuilder::new, (sb, v) -> {
    if (sb.length() != 0)
        sb.append(',');
    sb.append(v.longValue());
}, (a, b) -> a.length() == 0 ? b : b.length() != 0 ? a.append(',').append(b) : a, StringBuilder::toString));

回答by user2935131

Java 8 Solution would be like this:

Java 8 解决方案是这样的:

Stream.of(1,2,3,4).map(String::valueOf).collect(Collectors.joining("-"))

回答by Mehdi

For Java 7 or earlier.

对于 Java 7 或更早版本。

public static StringBuilder join(CharSequence delimiter, int... arr) {
    if (null == delimiter || null == arr) throw new NullPointerException();

    StringBuilder sb = new StringBuilder(String.valueOf(arr[0]));
    for (int i = 1; i < arr.length; i++) sb.append(delimiter).append(arr[i]);

    return sb;
}

public static void main(String[] args) {
    StringBuilder sb = join(" - ", 1, 2, 3, 4);
    System.out.println(sb.toString());//you could pass sb also coz println automatically call toString method within it
    System.out.println(sb.insert(0, "[").append("]"));
}

Output:

1 - 2 - 3 - 4

[1 - 2 - 3 - 4]

输出:

1 - 2 - 3 - 4

[1 - 2 - 3 - 4]