What is the best way to convert an int array to String in Java?

Asked

Viewed 422 times

3

What is the best method to convert {1, 2, 3, 4, 5} for "12345" ?

Example:

int[] array = {1, 2, 3, 4, 5};
array.toString(); // Existe alguma função que faça isso?

I know you can do it with a for loop but maybe you have better options.

int[] array = {1, 2, 3, 4, 5};
String s = ""; // Sei que tem StringBuilder também
for (int i : array) {
    s += i;
}

  • Have you tried Arrays.toString(array) of java.util.Arrays ?

  • 1

    In a loop, StringBuilder is better than concatenating strings with +: https://answall.com/q/71517/112052

  • 2

    @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

  • 1

    @hkotsubo yes yes, I made a test here and checked it, that it would not serve such purpose.

  • 2

    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 :-)

4 answers

5

Here’s a code that can help you:

import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        String resposta = IntStream.of(array).mapToObj(String::valueOf).reduce("", String::concat);
        System.out.println(resposta);
    }
}

See here working on Ideone.

His idea is to first convert the array into one IntStream and then in a Stream of Strings, using the String.valueOf(int) to convert int in String. Finally, the reduce concatenates all the Stringresulting s (using the method concat in one.

Although to be honest, probably the solution using a for and a StringBuilder will be the one with the best performance.

  • I tested your code in an array of 100 thousand units and it was more than 100x slower than using a Stringbuilder : Arrays.toString(array).replaceAll("([\\[\\], ])", ""); It is a 5x faster than yours and has a smaller code (but it is still much slower than with Stringbuilder so I will continue using it) but I found interesting this method for small arrays, anyway thanks for the knowledge friend

  • 1

    @unsightly Smaller code is not necessarily better, and use replace is gambiarra (can even "work" for this specific case, but what if it’s a string array and one of them has a [ in the middle of the text, it will be improperly removed, among other cases that can give problem, as arrays of arrays, for example). Using streams or a simple loop is best because you will have full control of the format and does not depend on implementation details toString - see more at https://answall.com/q/212754/112052

  • @hkotsubo I know, I will continue using the StringBuilder for being more readable and fast, I just found the creative solution

2


I think the best way in both legibility and efficiency is to use StringBuilder even, thanks for the help there people.

int[] array = {1, 2, 3, 4, 5};
StringBuilder sb = new StringBuilder();
for (int i : array) sb.append(i);

2

If you are using Java 8, you can use stream:

    String str = Arrays.stream(intArray).mapToObj(String::valueOf)
        .reduce((a, b) -> a.concat(b)).get();

If you need a char to concatenate you can use the Concat

    a.concat(",").concat(b)

2

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).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.