Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print all elements of String array in Kotlin in a single line?

Tags:

java

kotlin

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

like image 986
Dishonered Avatar asked Apr 18 '18 12:04

Dishonered


People also ask

How do I print an entire string array?

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.

How do you print each element of an array to a different line?

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.

How do I print a string array in one line?

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.


2 Answers

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) 
like image 99
Michael Avatar answered Sep 19 '22 19:09

Michael


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.

like image 32
delitescere Avatar answered Sep 17 '22 19:09

delitescere