[wp_ad_camp_1]
This post shows how to convert a comma-separated strings (CSV
s) to a list and back. In Kotlin
, we can create both immutable or mutable lists.
Requirements
IntelliJ
IDEA
Ultimate 2016.3- The
Community Edition
may be enough but we have not tried it.
- The
Kotlin
Version 1.1- Windows 10 Enterprise
CSV String to list
[wp_ad_camp_2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package exercise01 fun main(args: Array<String>) { val alphabet: String = "A,B,C,B,E,F" val regex = "\\s*,\\s*" val immutableList: List<String> = alphabet.split(regex).toList() val mutableList = alphabet.split(regex).toMutableList() print("Immutable List: " + immutableList) print("\n") print("Mutable List: " +mutableList) mutableList.add("G") print("\n") print("Updated Mutable List: " +mutableList) } |
Outputs:
1 2 3 | Immutable List: [A,B,C,B,E,F] Mutable List: [A,B,C,B,E,F] Updated Mutable List: [A,B,C,B,E,F, G] |
List to CSV string
[wp_ad_camp_3]
1 2 3 4 5 6 7 8 9 10 11 | package exercise01 fun main(args: Array<String>) { val immutableList = listOf("A", "B", "C", "D", "E", "F") val alphabet: String = immutableList.joinToString { e -> e } print(alphabet) } |
Outputs:
1 | A, B, C, D, E, F |
References
[wp_ad_camp_4]