List access

There are a number of ways to access list elements, most of which are similar to the ways in which we access arrays. We can access each element of the list by using either the [ ] subscript operator or the get function:

val listOfString = listOf<String>("One", "Two", "Three", "Four", "Three", "Five")
var element = listOfString[0]
element = listOfString.get(1)

listOfString[0] returns One and listOfString.get(1) returns Two.

We can get the index of a specific value in the list using the indexOf function. The following function, for example, will return 2:

var index = listOfString.indexOf("Three")

If the list contains more elements of the same type, the indexOf function will return the index of the first element. The lastIndexOf function, however, can return the index of the last occurrence of a specific element:

fun readListByIndex(){

val listOfString = listOf<String>("One","Two","Three","Four","Five","Three")

var element = listOfString[0]
println(element)

element = listOfString.get(1)
println(element)

var index = listOfString.indexOf("Three")
println(index)

index = listOfString.lastIndexOf("Three")
println(index)

println("With subscript [] operator")
for (i in 0 until listOfString.size) {
println("At index $i Value ${listOfString[i]}")
}

for (element in listOfString){
println("Value $element at index ${listOfString.indexOf(element)}")
}
}

The get function returns the element at a specific index, while the indexOf function returns the index number of a specific element.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.141.75