Home > Enterprise >  Convert a List of Integers to List of String in Kotlin
Convert a List of Integers to List of String in Kotlin

Time:10-21

I have a List like [1,2,3,4,5] and I am trying to convert to List ["1","2","3","4","5"]

I tried doing it like this

   val numbers = listOf(1, 2, 3, 4, 5)
   val numbersStr = mutableListOf<String>()
   
   val itr = numbers.listIterator()
   while(itr.hasNext())
    {
        numbersStr.add(itr.next().toString())
    }

but I feel it is little verbose and doesnt make use of Kotlin's built in functions.

What is the best alternative?

CodePudding user response:

Check out kotlin's map function

val numberStr = listOf(1, 2, 3, 4, 5).map { it.toString() }
  • Related