简体   繁体   English

如何使用Google Guava(Java)加入阵列?

[英]How can I join an array using Google Guava (Java)?

I am trying to join int[] (array of int) using Google Guava's Joiner class. 我正在尝试使用Google Guava的Joiner类加入int[] (int数组)。

Example: 例:

int[] array = { 1, 2, 3 };
String s = Joiner.on(", ").join(array);  // not allowed

I checked StackOverflow and Google. 我检查了StackOverflow和Google。 There is no "one-liner" in foundation classes to convert int[] to Integer[] or List<Integer> . 基础类中没有“一线”将int[]转换为Integer[]List<Integer> It always requires a for loop, or your own hand-rolled helper function. 它总是需要一个for循环,或者你自己的手动辅助函数。

Any advice? 有什么建议?

Ints is a Guava library containing helper functions. Ints是一个包含辅助函数的Guava库。

Given int[] array = { 1, 2, 3 } you can use the following: 给定int[] array = { 1, 2, 3 }您可以使用以下内容:

String s = Joiner.on(", ").join(Ints.asList(array));

Or more succinctly: 或者更简洁:

String s = Ints.join(", ", array);

静态方法Ints.join(String separator, int... array)也应该有效。

The reason they did not add a signature for join(int[]) is that then they would have had to add one for each primitive type. 他们没有为join(int[])添加签名的原因是他们必须为每个基本类型添加一个。 Since autoboxing works automatically to convert Integer to int you can pass in an Integer[] . 由于autoboxing自动将Integer转换为int ,因此可以传入Integer[]

As you said, use Ints.asList(array) to get an Iterable<Integer> from your int[] . 如上所述,使用Ints.asList(array)int[]获取Iterable<Integer>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM