简体   繁体   中英

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.

Example:

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

I checked StackOverflow and Google. There is no "one-liner" in foundation classes to convert int[] to Integer[] or List<Integer> . It always requires a for loop, or your own hand-rolled helper function.

Any advice?

Ints is a Guava library containing helper functions.

Given int[] array = { 1, 2, 3 } you can use the following:

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. Since autoboxing works automatically to convert Integer to int you can pass in an Integer[] .

As you said, use Ints.asList(array) to get an Iterable<Integer> from your int[] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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