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

67 Views Asked by At

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
3

There are 3 best solutions below

0
Rifat Rubayatul Islam On BEST ANSWER

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());
0
Basil Bourque On

tl;dr

One-liner:

String.join ( 
    " " , 
    Arrays.stream ( ints ).mapToObj ( String :: valueOf ).toArray ( String[] :: new ) 
)

0 1 2 3 4 5

Details

Make some sample data.

int[] ints = IntStream.rangeClosed ( 0 , 5 ).toArray ( );

Convert each int primitive value to text, each piece of text being a single character, a String-based version of our number. Collect these String objects into an array.

String[] strings = Arrays.stream ( ints ).mapToObj ( String :: valueOf ).toArray ( String[] :: new );

Join the strings in that array together, separated on the interior only by a SPACE character. No trailing SPACE, a convenient benefit of String.join.

String result = String.join ( " " , strings );

Put that all together.

int[] ints = IntStream.rangeClosed ( 0 , 5 ).toArray ( );
String[] strings = Arrays.stream ( ints ).mapToObj ( String :: valueOf ).toArray ( String[] :: new );
String result = String.join ( " " , strings );
System.out.println ( "result = " + result );

See this code run at Ideone.com.

result = 0 1 2 3 4 5

0
Thiyagu On

If using a StringBuilder is not a requirement, then you could do as follows.

Calling Arrays.stream() will return an IntStream. Using mapToObj with String::valueOf as the mapper will convert the primitive int to a String. This will return a Stream<String>. Finally, using Collectors.joining, we can concatenate the individual string elements of the stream with a space.

 String result = Arrays.stream(a)
        .mapToObj(String::valueOf)
        .collect(Collectors.joining(" "));