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




KOTLIN - COPY FROM SET


How to copy one Set to the other?


There are two ways by which we can copy one Set to the other.

  1. Using the method 'toSet()'


  2. Using the method 'toMutableSet()'


Let us look at the first way using the toSet() method.


Example :



fun main() {
    val x = mutableSetOf("Mohan", "Kriti", "Salim")
    var y = x.toSet()
    println("The Copied Set is "+y)
}


Output :



  The Copied Set is [Mohan, Kriti, Salim]

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


val x = mutableSetOf("Mohan", "Kriti", "Salim")

Below is how the values are positioned in the Set,

java_Collections

Then we have used the toSet() method and create a new Set that would be the exact copy of x.


Then assign it to y.


	var y = x.toSet()
java_Collections


And we get the below output,


The Copied Set is [Mohan, Kriti, Salim]

The toMutableSet() is exactly same as toSet() method. Just that toMutableSet() creates a set that can be changed.


Note : Do not use the '=' operator to copy a Set to the other(i.e. If there are two Sets 'x' and 'y'. Do not use y = x). Because in that case any changes made to the Set 'x' will be reflected in the copied Set 'y'.