Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




KOTLIN - ACCESSING SET


Accessing the elements of the 'Set' using elementAt() method


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.


Example :



fun main() {
    var x = setOf(5, "John", "Kotlin")
    println(x.elementAt(1))
}


Output :



  John

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))

Accessing first and last elements of the 'Set' using first() and last() method


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.


Example :



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())
}


Output :



  The first element in the Set is : 5
  The last element in the Set is : Kotlin

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.