How to create a Mutable List of Alphabets in Kotlin?

Viewed 1543

I want to create a MutableList of alphabets form A to Z but so far I can only think of the following method as the shortest one without writing each and every alphabet.

fun main()
{
    var alphabets: MutableList<Char> = mutableListOf()

    for (a in 'A'..'Z')
    {
        alphabets.add(a)
    }
    print(alphabets)
}

So I wanted to know if there is any Lambda implementation or shorter method for the same?

3 Answers

You can use CharRange() or using .. operator to create a range.

For example:

val alphabets = ('A'..'Z').toMutableList()
print(alphabets)
// [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]

or

 val alphabets = CharRange('A','Z').toMutableList()
 print(alphabets)
 // [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]

You can use rangeTo extension function as below

private val alphabets = ('A').rangeTo('Z').toMutableList()
println(alphabets)
[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]

Alternatively, you can use ('a'..'z').joinToString("").

val abc = ('a'..'z').joinToString("")
println(abc) //abcdefghijklmnopqrstuvwxyz

You can perform the same functions on a string in Kotlin as you can perform on a list of characters

For example:

for (i in abc) { println(i) }

This lists each alphabet individually on a new line just as it would if you converted it into a list.

Related