Just to complement the other answers, from Java 8 you can use String.join
. But as this method should receive one or more instances of CharSequence
and int
's are not CharSequence
's, we still have to convert the array of int
to an array of String
:
int[] array = { 1, 2, 3, 4, 5 };
String s = String.join("", IntStream.of(array).mapToObj(String::valueOf).toArray(String[]::new));
System.out.println(s); // 12345
Although in this case, I still prefer the solution that uses a loop and a StringBuilder
, that is better than concatenation with +
(and both in turn, are faster than streams).
Other option (which only works if the array values are all numbers between 0 and 9) is to build a number with the array digits and at the end convert it to String
:
int[] array = { 1, 2, 3, 4, 5 };
int n = 0;
for (int i : array) {
n *= 10;
n += i;
}
String result = String.format("%0" + array.length + "d", n); // 12345
I used String.format
to put the zeros on the left, if the first elements of the array are 0
(because if I just print the number directly, it is shown without the zeroes on the left). I also use the array size (array.length
) so that the amount of digits shown is the same amount as in the array (so an array like {0, 0, 0, 1}
results in the string 0001
).
Have you tried
Arrays.toString(array)
ofjava.util.Arrays
?– Luiz Augusto
In a loop,
StringBuilder
is better than concatenating strings with+
: https://answall.com/q/71517/112052– hkotsubo
@Luizaugusto If I’m not mistaken,
Arrays.toString
places a comma between the elements, but the question asks to join the numbers, without any separator– hkotsubo
@hkotsubo yes yes, I made a test here and checked it, that it would not serve such purpose.
– Luiz Augusto
And the answer below is a valid option, but I do not know if it is "the best way" (assuming that performance is a criterion to consider "better", so it is not, because streams are slower than a simple loop). But those who like a "more functional footprint" will surely find it best :-)
– hkotsubo