Reputation: 21319
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?
Upvotes: 14
Views: 8785
Reputation: 6801
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);
Upvotes: 32
Reputation: 644
Static method Ints.join(String separator, int... array)
should also work.
Upvotes: 23
Reputation: 32969
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[]
.
Upvotes: 0