Skip to content Skip to sidebar Skip to footer

Capitalize Each Word In Kotlin Arraylist

I know to capitalize the arraylist with strings as data can be done with list.map({ it.capitalize()})which returns as a list. Now, what if it's a data class instead of strings? c

Solution 1:

The first option is adding a capitalized name while creating animal object. If that's not possible then you can pass animals list like this

recyclerView.adapter = AnimalAdapter(this, animals.map({Animals(it.name.capitalize(),it.type)}));

Solution 2:

Depending on what your needs are, you could either create an Animal object with already capitalized values:

class Animal(name: String, type: String) {
    val name: String = name.capitalize()
    val type: String = type.capitalize()
}

Note that in this case the Animal class is not a data class any more.

or map your list of animals before using it:

val mappedAnimals = animals.map { Animal(it.name.capitalize(), it.type.capitalize()) }
recyclerView.adapter = AnimalAdapter(this, mappedAnimals)

Solution 3:

I wouldn't use mapping to capitalise all strings. Actually, there is a better approach. You can capitalise those strings in a TextView, at view level.

Why do I think it is a better approach than changing your data?

You do not modify data. Now, your mapped model is different that original. It can be a source of mistakes, because Animal("Dog", "John") != Animal("DOG", "JOHN"). Also, when you change Animal class there is a chance that somewhere you should change something too.

Making the capitalisation at view level makes it much more easier to read, find and modify.

And it's easy:

<TextView>
    ...
    android:textAllCaps=true
</TextView>

@see: https://developer.android.com/reference/android/widget/TextView.html#attr_android:textAllCaps

Post a Comment for "Capitalize Each Word In Kotlin Arraylist"