Home > other >  How to display an array in one line without using the method ToString();
How to display an array in one line without using the method ToString();

Time:02-05

I have an array, for example a[]=[10,5,3,1]. I would like to display the elements of this array as follows: 10, 5, 3, 1 How to display it in one line? without using the method ToString() or other array class built-in methods.

I wanted to write system.out.println (for ...). However, it is not possible to put for as an argument of printing.

CodePudding user response:

You could loop over the array and call System.out.print:

for (int i = 0; i < a.length;   i) {
    System.out.print(i   " ");
}

CodePudding user response:

Answer by Murelink is correct. Another approach uses streams, IntStream specifically.

Arrays
.stream( myIntArray )
.forEach( x -> { System.out.print( x   " ") ; } ) ; 

CodePudding user response:

int[] arr = { 10, 5, 3, 1 };

String str = Arrays.stream(arr).mapToObj(String::valueOf)
                   .collect(Collectors.joining(","));
System.out.println(str); // 10,5,3,1

str = Arrays.stream(arr).mapToObj(String::valueOf)
            .collect(Collectors.joining(",", "[", "]"));
System.out.println(str); // [10,5,3,1]
  • Related