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




LIST - slice()


slice() method is used to access a chunk of elements from the 'List'.


Let us take the above example, where we have the 'List' with five values, 'Mohan', 'John', 'Paul', 'Kriti' and 'Salim'. And we want to access the second, third and fourth element i.e. 'John', 'Paul' and 'Kriti'.


Example :



fun main() {
    var x = listOf("Mohan", "John", "Paul", "Kriti", "Salim")
    println(x.slice(1..3))
} 


Output :



 [John, Paul, Kriti]

So, in the above code we have created a 'List' and initialised to the variable 'x'.


var x = listOf("Mohan", "John", "Paul", "Kriti", "Salim")

Now, let us see, how the values are positioned in the List


java_Collections

So, as we can see the elements are positioned as '0', '1', '2', '3' and '4'.


Now, if we want to access the second, third and fourth element (i.e. 'John', 'Paul' and 'Kriti').


We can specify the range using 'slice()' method.


i.e. x.slice(1..3)


'x.slice(1..3)' actually tells, to pick the elements from index/position '1' to the index/position 3.


java_Collections

And the print statement prints the second, third and fourth element (i.e. 'John', 'Paul' and 'Kriti').


println(x.slice(1..3))

Output :



 ['John', 'Paul', 'Kriti']

So, if you look at the above output, the values are enclosed within square brackets '[]'. That is because a new array is created with the three elements 'John', 'Paul' and 'Kriti'.


Note : The 'slice()' method creates a new array with the new values.

set()


Change/Replace an Item in a List using set() method


Let us take the same example, where we have a List that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to replace the name 'Kriti' with a new name 'Paul'.


Example :



fun main() {
    var x = mutableListOf("Mohan", "Kriti", "Salim")
    x.set(1, "Paul")
    println(x)
} 


Output :



 [Mohan, Paul, Salim]

So, in the above code we have created a 'List' using 'mutableListOf()' method, because we need to replace an element in the List.


var x = mutableListOf("Mohan", "Kriti", "Salim")

Caution : Use 'mutableListOf()' method and not 'listOf()' method.

Now, let us see, how the values are positioned in the List


java_Collections

Now, if we see the above diagram, 'Kriti' resides at position/index '1'. So, what we do is,use the 'set()' method specifying the position/index '1' and the new name 'Paul'.


x.set(1, "Paul")

java_Collections

And we get the below output,


[Mohan, Paul, Salim]