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




KOTLIN - REPLACE LIST ELEMENTS


Change/Replace an Item in a List using index


Let us say, 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[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, just replace the position/index '1' (i.e. x[1]) with the new name 'Paul'.


x[1] = "Paul"

java_Collections

And we get the below output,


[Mohan, Paul, Salim]

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]