How to iterate over a list of Strings and concatenate them in Kotlin?

Viewed 7753

I have a list of strings such as:

listOf("1", "2", "3", "4", "+", "3")

And I want to concatenate so that I only get the numbers: "1234". I first attempted using a for loop which worked.

However I was wondering if Kotlin had a way of one lining the whole thing using a nice one line like:

val myList = listOf("1", "2", "3", "4", "+", "3")
someConcatenationFunction(myList) // returns "1234"
3 Answers

The solution I have found is this (to be put like in a separate file):

fun List<String>.concat() = this.joinToString("") { it }.takeWhile { it.isDigit() }

So basically, what it does is:

  • joinToString("") : JoinToString joins the content of a list to a String, the "" specifies that you don't want any separators in the concatenated String.
  • { it }.takeWhile { it.isDigit() } : means that from the concatenated list, I only want the Chars that are digits. takeWhile will stop at first non digit.

And here you go! Now you can simply do:

listOf("1", "2", "3", "4", "+", "3").concat() // returns "1234"

Just using function joinToString() conact all the list items applicable for both Char and String. below is the eg.

val list = listOf("1", "2", "3", "4", "+", "5")
val separator = ","
val string = list.joinToString(separator)
println(string)        //output: 1,2,3,4,+,5

Other eg.

val list = listOf("My", "Name", "is", "Alise")
val separator = " "
val string = list.joinToString(separator)
println(string)        //outeput: My Name is Alisse

You don't clearly said so but I assume you want to concat integers as long as possible (I.e. stop once an invalid string is encountered. The most straighforward way to do this:

val data = listOf("1", "2", "3", "4", "+", "3")
val concat = data.takeWhile { it.toIntOrNull() != null }.joinToString("")
Related