We have the Set with three values, 5, John and Kotlin. And we want to access the second element i.e. John using the elementAt() method.
fun main() { var x = setOf(5, "John", "Kotlin") println(x.elementAt(1)) }
So, in the above code we have created a Set and initialised to the variable x.
var x = setOf(5, "John", "Kotlin")
Now, let us see, how the values are positioned in the Set,
x ------- 0 1 2 | | | | | | V V V +----------+ +----------+ +----------+ | | | | | | | 5 | | John | | Kotlin | | | | | | | +----------+ +----------+ +----------+
So, as we can see the elements are positioned as 0, 1 and 2. And if we want to access the second element, we can refer to the position/index 1 using the elementAt() method (i.e. x.elementAt(1)).
And the print statement prints the value of the second element of the Set (i.e. John).
println(x.elementAt(1))
Let us take the same example where we have a Set with three values, 5, John and Kotlin. And we want to access the first element element i.e. 5 and last element i.e. Kotlin.
fun main() { var x = setOf(5, "John", "Kotlin") println("The first element in the Set is : "+x.first()) println("The last element in the Set is : "+x.last()) }
The above code is quite self explanatory.
The first() method is used to get the first element in the Set.
println("The first element in the Set is : "+x.first())
The last() method is used to get the last element from the Set.