简体   繁体   中英

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

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

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.

You can achieve this using "contentToString" method:

var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
  println(someList.contentToString())

O/p:
[United, Chelsea, Liverpool]e

I know three ways to do this:

(0 until someList.size).forEach { print(someList[it]) }
someList.forEach { print(it) }
someList.forEach(::print)

Hope you enjoyed it :)

You can do the same:

fun main(args : Array<String>){
    var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
    someList.forEach(System.out::print)
}

You could

fun main(args : Array<String>){
  var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")

  val sb = StringBuilder()
  for (element in someList) {
      sb.append(element).append(", ")
  }
  val c = sb.toString().substring(0, sb.length-2)
  println(c)
}

gives

United, Chelsea, Liverpool

alternatively you can use

print(element)

in the for loop, or even easier use:

var d = someList.joinToString()
println(d)

If it is solely for printing purpose then a good one liner is

 var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
 println(java.util.Arrays.toString(someList))

Simply do this, no need to use loop and iterate by yourself. Reference

println(someList.joinToString(","))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM