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




KOTLIN - INSERT IN LIST


How to insert a new Item in a List?


Let us say, we have a List that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to insert a new name 'Nikhil' in between 'Mohan' and 'Kriti'.


We can achieve that using the 'add()' Function.


Example :



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


Output :



 [Mohan, Nikhil, Kriti, Salim]

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


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

Below is 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,just insert the new name 'Nikhil' at the position/index '1' using the 'add()' Function.


And 'Kriti' gets shifted to index/position '2'.


x.add(1,"Nikhil")

java_Collections

And we get the below output,


[Mohan, Nikhil, Kriti, Salim]

How to insert a new Item at the end of the List?


Let us say, we have a List that contains three names, 'Mohan', 'Kriti' and 'Salim'. And we want to insert a new name 'Mika' at the end of the List.


We can use the 'add()' Function without any parameter to achieve the above.


Example :



fun main() {
    var x = mutableListOf("Mohan", "Kriti", "Salim")
    x.add("Mika")
    println(x)
} 


Output :



 [Mohan, Kriti, Salim, Mika]

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


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

Below is how the values are positioned in the List,


java_Collections

Next, we have used the 'add()' function to add the new name 'Mika' at the end of the List.


x.add("Mika")

java_Collections

And we get the below output,


[Mohan, Kriti, Salim, Mika]