This is my code
fun main(args : Array<String>){ var someList : Array<String> = arrayOf("United","Chelsea","Liverpool") //How do i print the elements using the print method in a single line? }
In java i would do something like this
someList.forEach(java.lang.System.out::print);
We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.
To print the array elements on a separate line, we can use the printf command with the %s format specifier and newline character \n in Bash. @$ expands the each element in the array as a separate argument. %s is a format specifier for a string that adds a placeholder to the array element.
Print Array in One Line with Java StreamsArrays. toString() and Arrays. toDeepString() just print the contents in a fixed manner and were added as convenience methods that remove the need for you to create a manual for loop.
Array
has a forEach
method as well which can take a lambda:
var someList : Array<String> = arrayOf("United","Chelsea","Liverpool") someList.forEach { System.out.print(it) }
or a method reference:
var someList : Array<String> = arrayOf("United","Chelsea","Liverpool") someList.forEach(System.out::print)
Idiomatically:
fun main(args: Array<String>) { val someList = arrayOf("United", "Chelsea", "Liverpool") println(someList.joinToString(" ")) }
This makes use of type inference, an immutable value, and well-defined methods for doing well-defined tasks.
The joinToString()
method also allows prefix and suffix to be included, a limit, and truncation indicator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With