Search code examples
javajava-streamstringbuilder

How to add all the elements of an int[] to a StringBuilder using a stream, adding extra space to each of the element


I am trying to add all the elements of an int array brr into a StringBuilder res using the following code:

StringBuilder res = new StringBuilder();

Arrays.stream(brr).forEach(res::append);

I want the StringBuilder to be:

0 1 2 3 4 5

However, it is actually:

012345

Solution

  • If you don't mind the trailing space, you can do this

    Arrays.stream(brr).forEach(i -> res.append(i).append(" "));
    

    You can trim the string if you don't want to print the trailing space

    System.out.println(res.toString().trim());