Kotlin list : listOf()
In Kotlin, listOf() is a function that is used to create an immutable list of elements. The listOf() function takes a variable number of arguments and returns a new list containing those arguments. Here’s an example:
Kotlin
val numbers = listOf( 1 , 2 , 3 , 4 , 5 ) |
In this example, we create a new list called numbers using the listOf() function. The list contains five elements: the integers 1 through 5. Since the list is immutable, we cannot modify its contents once it has been created.
We can access elements of the list using indexing, like this:
Kotlin
val firstNumber = numbers[ 0 ] // returns 1 val lastNumber = numbers[numbers.size - 1 ] // returns 5 |
In this example, we use indexing to access the first and last elements of the numbers list. Note that indexing is 0-based in Kotlin, so the first element has an index of 0 and the last element has an index of numbers.size – 1.
We can also iterate over the list using a for loop, like this:
Kotlin
for (number in numbers) { println(number) } |
In this example, we use a for loop to iterate over the numbers list and print each element to the console.
Overall, the listOf() function is a simple and convenient way to create immutable lists of elements in Kotlin. It is particularly useful for situations where you need to store a fixed set of data that will not change during the runtime of your program.
Here are some advantages and disadvantages of using the listOf() function in Kotlin:
Advantages:
- Immutability: The listOf() function creates an immutable list, which means that the contents of the list cannot be modified once it has been created. This makes it easier to reason about the behavior of your code and can help prevent bugs caused by unintended changes to the list.
- Type safety: Since Kotlin is a statically typed language, the listOf() function provides type safety by ensuring that all elements of the list are of the same type. This can help prevent errors caused by passing the wrong type of data to a function or method.
- Convenience: The listOf() function is a simple and convenient way to create lists of elements in Kotlin. It takes a variable number of arguments, which makes it easy to create a list of elements without having to write a lot of boilerplate code.
Disadvantages:
- Immutability: While immutability can be an advantage in some cases, it can also be a disadvantage in situations where you need to modify the contents of a list during the runtime of your program. If you need to modify a list, you will need to use a mutable list instead of an immutable one.
- Performance overhead: Immutable lists can have some performance overhead compared to mutable lists or arrays, especially if you need to perform a lot of operations on the list. This is because each operation on an immutable list requires the creation of a new list object, which can be expensive in terms of memory and processing time.
- Limited functionality: The listOf() function creates a basic immutable list with limited functionality. If you need more advanced features, such as the ability to add or remove elements from the list, you will need to use a mutable list instead.
Overall, the listOf() function is a useful tool for creating immutable lists of elements in Kotlin, but it is not suitable for every situation. Its - advantages include immutability, type safety, and convenience, while its disadvantages include limited functionality and potential performance overhead. When deciding whether to use listOf() in your code, it’s important to consider the specific needs of your program and choose the appropriate data structure accordingly.
A list is a generic ordered collection of elements. Kotlin has two types of lists, immutable lists (cannot be modified) and mutable lists (can be modified).
Read-only lists are created with listOf() whose elements can not be modified and mutable lists created with mutableListOf() method where we alter or modify the elements of the list.
Kotlin program of list contains Integers –
Java
fun main(args: Array<String>) { val a = listOf( '1' , '2' , '3' ) println(a.size) println(a.indexOf( '2' )) println(a[ 2 ]) } |
Output:
3 1 3
Kotlin program of list contains Strings –
Java
fun main(args: Array<String>) { //creating list of strings val a = listOf( "Ram" , "Shyam" , "Raja" , "Rani" ) println( "The size of the list is: " +a.size) println( "The index of the element Raja is: " +a.indexOf( "Raja" )) println( "The element at index " +a[ 2 ]) for (i in a.indices){ println(a[i]) } } |
Output:
The size of the list is: 4 The index of the element Raja is: 2 The element at index Raja Ram Shyam Raja Rani
Indexing of Elements of List in Kotlin –
Each element of a list has an index. The first element has an index of zero (0) and the last Element has index
len – 1, where ‘len’ is the length of the list.
Java
fun main(args: Array<String>) { val numbers = listOf( 1 , 5 , 7 , 32 , 0 , 21 , 1 , 6 , 10 ) val num1 = numbers.get( 0 ) println(num1) val num2 = numbers[ 7 ] println(num2) val index1 = numbers.indexOf( 1 ) println( "The first index of number is $index1" ) val index2 = numbers.lastIndexOf( 1 ) println( "The last index of number is $index2" ) val index3 = numbers.lastIndex println( "The last index of the list is $index3" ) } |
Output:
1 6 The first index of number is 0 The last index of number is 6 The last index of the list is 8
First and Last Elements –
We can retrieve the first and the last elements of the list without using the get() method.
Considering the previous example, if we include the following code after line no. 17
Java
fun main(args: Array<String>) { val numbers = listOf( 1 , 5 , 7 , 32 , 0 , 21 , 1 , 6 , 10 ) println(numbers.first()) println(numbers.last()) } |
Output:
1 10
List Iteration methods –
It is process of accessing the elements of list one by one.
There are several ways of doing this in Kotlin.
Java
fun main(args: Array<String>) { val names = listOf( "Gopal" , "Asad" , "Shubham" , "Aditya" , "Devarsh" , "Nikhil" , "Gagan" ) // method 1 for (name in names) { print( "$name, " ) } println() // method 2 for (i in 0 until names.size) { print( "${names[i]} " ) } println() // method 3 names.forEachIndexed({i, j -> println( "names[$i] = $j" )}) // method 4 val it: ListIterator<String> = names.listIterator() while (it.hasNext()) { val i = it.next() print( "$i " ) } println() } |
Output:
Gopal, Asad, Shubham, Aditya, Devarsh, Nikhil, Gagan, Gopal Asad Shubham Aditya Devarsh Nikhil Gagan names[0] = Gopal names[1] = Asad names[2] = Shubham names[3] = Aditya names[4] = Devarsh names[5] = Nikhil names[6] = Gagan Gopal Asad Shubham Aditya Devarsh Nikhil Gagan
Explanation:
for (name in names) { print("$name, ") }
The for loop traverses the list. In each cycle, the variable ‘name’ points to the next element in the list.
for (i in 0 until names.size) { print("${names[i]} ") }
This method uses the size of the list. The until keyword creates a range of the list indexes.
names.forEachIndexed({i, j -> println("namess[$i] = $j")})
With the forEachIndexed() method, we loop over the list having index and value available in each iteration.
val it: ListIterator = names.listIterator() while (it.hasNext()) { val i = it.next() print("$i ") }
Here we use a ListIterator to iterate through the list.
Sorting the elements in list –
The following example show how to sort a list in ascending or descending order.
Java
fun main(args: Array<String>) { val list = listOf( 8 , 4 , 7 , 1 , 2 , 3 , 0 , 5 , 6 ) val asc = list.sorted() println(asc) val desc = list.sortedDescending() println(desc) } |
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8] [8, 7, 6, 5, 4, 3, 2, 1, 0]
Explanation:
val asc = list.sorted()
The sorted() method sorts the list in ascending order.
val desc = list.sortedDescending()
The sortedDescending() method sorts the list in descending order.
Contains() and containsAll() functions –
This method checks whether an element exists in the list or not.
Java
fun main(args: Array<String>) { val list = listOf( 8 , 4 , 7 , 1 , 2 , 3 , 0 , 5 , 6 ) val res = list.contains( 0 ) if (res) println( "The list contains 0" ) else println( "The list does not contain 0" ) val result = list.containsAll(listOf( 3 , - 1 )) if (result) println( "The list contains 3 and -1" ) else println( "The list does not contain 3 and -1" ) } |
Output:
The list contains 0 The list does not contain 3 and -1
Explanation:
val res = list.contains(0)
Checks whether the list contains 0 or not and returns true or false (her true) that is stored in res.
val result = list.containsAll(listOf(3, -1))
Checks whether the list contains 3 and -1 or not.