Conversion between Lists of different types in Kotlin
This article explores different ways to convert between lists of different types in Kotlin.
You can use the map() function to easily convert a list of one type to a list of another type. It returns a list containing the results of applying the specified transform function to each element in the original list.
For example, the following code converts a List<Integer> to a List<String>:
|
1 2 3 4 5 6 |
fun main() { val list: List<Int> = listOf(1, 2, 3, 4, 5) val newList: List<String> = list.map { it.toString() } println(newList) } |
Output:
[1, 2, 3, 4, 5]
To do the opposite, i.e. convert List<String> to List<Integer>, you can do like:
|
1 2 3 4 5 6 |
fun main() { val list: List<String> = listOf("1", "2", "3", "4", "5") val newList: List<Int> = list.map { it.toInt() } println(newList) } |
Output:
[1, 2, 3, 4, 5]
That’s all about conversion between lists of different types in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)