Initialize a list in Kotlin with specific value
This article explores different ways to initialize a list in Kotlin in a single line with the specified value.
There are several ways to initialize a list, as discussed below:
1. Using Collections.nCopies() function
The Collections.nCopies() function returns an immutable list of specified copies of the specified object.
|
1 2 3 4 5 6 7 8 9 10 |
import java.util.Collections fun main() { val size = 5 val value = 1 val ints: List<Int> = Collections.nCopies(size, value) println(ints) // [1, 1, 1, 1, 1] } |
To get a mutable list, you can do like:
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.Collections fun main() { val size = 5 val value = 1 val ints: MutableList<Int> = ArrayList(Collections.nCopies(size, value)) ints.removeFirst() println(ints) // [1, 1, 1, 1] } |
2. Using map() function
Here, the idea is to get a range of indices for the list and transform the indices into the given value using the map() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun <T> generate(size: Int, value: T): List<T> { return (0 until size).map { value } } fun main() { val size = 5 val value = 1 val ints: List<Int> = generate(size, value) println(ints) // [1, 1, 1, 1, 1] } |
To get a mutable list, you can use the toMutableList() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun <T> generate(size: Int, value: T): MutableList<T> { return (0 until size).map { value }.toMutableList() } fun main() { val size = 5 val value = 1 val ints: MutableList<Int> = generate(size, value) ints.removeFirst() println(ints) // [1, 1, 1, 1] } |
3. Using Array
Here, the idea is to create an array of the specified size and use the native fill() function to initialize it with a given value. Then use toList() function to get an immutable list.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val size = 5 val value = 1 val data = arrayOfNulls<Int>(size) data.fill(value) val ints: List<Int> = data.toList() as List<Int> println(ints) // [1, 1, 1, 1, 1] } |
To get a mutable list, you can use the toMutableList() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val size = 5 val value = 1 val data = arrayOfNulls<Int>(size) data.fill(value) val ints: MutableList<Int> = data.toMutableList() as MutableList<Int> ints.removeLast() println(ints) // [1, 1, 1, 1] } |
That’s all about initializing a list in Kotlin with the specified value.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)