Home > database >  How to make each element in a list lowercase in Kotlin?
How to make each element in a list lowercase in Kotlin?

Time:12-10

I have the following function: fun listToLowerCase(names: List) {}

I wish to make the "names" list lowercase in-place something like: names = names.map { it.lowercase() }

Need Kotlin examples for the same. What would be the most efficient approach and why?

CodePudding user response:

The following works. Why overthink the problems?

fun main(args: Array<String>) {
    val names = listOf("Name1", "Name2", "Name3")
    print(listToLowerCase(names))
}

fun listToLowerCase(names: List<String>): List<String> {
    return names.map { it.lowercase() }
}

CodePudding user response:

You can also define an extension:

// An extension function for List<String>:
fun List<String>.lowerCase(): List<String> = this.map { it.lowercase() }

Then you can use it like this:

val lowerCaseList = listOf("Banana", "Pineapple", "Orange").lowerCase()
println(lowerCaseList)

In terms of efficiency, the map approach is very similar to using a for loop. And since it is definitely more redeable and less error prone, you should go with it.

CodePudding user response:

You cannot modify a List<*> in-place in Kotlin because this type represents read-only lists.

It's more common in Kotlin to use a functional approach for this and return a new List, instead. As you have stated, this can be accomplised with a simple map { it.lowercase() }.

If you really really want to do it in-place, you'll need to work with a MutableList:

fun listToLowerCase(names: MutableList<String>) {
    for (i in names.indices) {
        names[i] = names[i].lowercase()
    }
}

Which you can then use like this:

val list = mutableListOf("Bob", "George", "FRED")
listToLowerCase(list) // mutates the list
println(list) // [bob, george, fred]
  • Related