This Kotlin tutorial gives you a simple example that helps to convert comma-separated String into List & List into one String.
Related Post: Kotlin List & Mutable List tutorial with examples
>>> Refer to: JavaSampleApproach.com
I. Technology
– Java 1.8
– Kotlin 1.1.2
II. Practice
1. String into List
Use CharSequence.split()
method that returns a List
, then map()
each item with CharSequence.trim()
method to remove [space] character.
1 2 3 4 5 6 |
val input: String = "One, Two, Three, Four" println("=== String into List ===") var result: List<String> = input.split(",").map { it.trim() } result.forEach { println(it) } |
Result:
1 2 3 4 5 |
=== String into List === One Two Three Four |
2. List into String
Use joinToString()
method with prefix
, postfix
, limit 3 elements to be appended, and truncated by string “…more…”:
1 2 3 4 5 6 7 |
val result = listOf("One", "Two", "Three", "Four") println(result) println("=== List into String ===") val output = result.joinToString("|", prefix = "<", postfix = ">", limit = 3, truncated = "...more...") println(output) |
Result:
1 2 3 |
[One, Two, Three, Four] === List into String === <One|Two|Three|...more...> |