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




LIST - subList()


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


Say, 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.subList(1,4))
} 


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 'subList()' method.


i.e. x.subList(1,4)


'x.subList(1,4)' actually tells, to pick the elements from index/position '1' to the index/position '4-1' i.e. 3.


java_Collections

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


println(x.subList(1,4))

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 'subList()' method creates a new array with the new values.