Generate a List of consecutive integers in Kotlin
This article explores different ways to generate a list of consecutive integers in Kotlin.
1. Using List constructor
The List constructor creates a new list with the specified size, where each element is calculated by calling the specified function sequentially starting from the beginning. Here’s how the code would look like:
|
1 2 3 4 5 6 7 |
fun main() { val n = 5 val list = List(n) { it + 1 } println(list) // [1, 2, 3, 4, 5] } |
2. Using Kotlin Ranges
Another alternative uses the Kotlin Range to generate a range of increasing integers between the specified indices, and then collect all elements into a list.
|
1 2 3 4 5 6 7 |
fun main() { val n = 5 val list = (1.. n).toList() println(list) // [1, 2, 3, 4, 5] } |
Alternatively, you can generate the Kotlin range of the list’s size and map each value to the next number in a sequence.
|
1 2 3 4 5 6 7 |
fun main() { val n = 5 val list = (0 until n).map { it + 1 } println(list) // [1, 2, 3, 4, 5] } |
To fill an “existing” list with the increasing integer sequence, do as follows:
|
1 2 3 4 5 6 7 8 |
fun main() { val n = 5 val list = MutableList(n) {0} (1.. n).forEach { list[it - 1] = it } println(list) // [1, 2, 3, 4, 5] } |
Or, start from index 0:
|
1 2 3 4 5 6 7 8 |
fun main() { val n = 5 val list = MutableList(n) {0} (0 until n).forEach { list[it] = it + 1 } println(list) // [1, 2, 3, 4, 5] } |
That’s all about generating a list of consecutive integers in Kotlin.
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 :)