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




KOTLIN - JOIN TWO SETS


How to extend an existing Set or join two Sets?


Let us say, we have a Set that contains three names, Mohan, Kriti and Salim. And we want to insert a new Set with two names Sia and Andrew at the end of the Set.


There are two ways by which we can join or extend Set.

  1. By using the + operator

  2. Using the addAll() Function


At first let us see the Joining of two Sets using + operator.


Example :



fun main() {
    var x = mutableSetOf("Mohan", "Kriti", "Salim")
    var y = mutableSetOf("Sia", "Andrew")
    var z = x + y
    println(z)
} 


Output :



  [Mohan, Kriti, Salim, Sia, Andrew]

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


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

Below is how the values are positioned in the Set,

java_Collections

Also we have another Set that contains, Sia and Andrew.


	var y = mutableSetOf("Sia", "Andrew")
java_Collections


Next, we have used the + operator to add the the Sets x and y.


var z = x + y

And the Sets x and yis joined and initialised to a new Set z.

java_Collections

And we get the below output,


[Mohan, Kriti, Salim, Sia, Andrew]

Let us rewrite the same example using the addAll() Function.


Example :



fun main() {
    var x = mutableSetOf("Mohan", "Kriti", "Salim")
    var y = mutableSetOf("Sia", "Andrew")
    x.addAll(y)
    println(x)
}


Output :



  [Mohan, Kriti, Salim, Sia, Andrew]

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


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

Below is how the values are positioned in the Set,

java_Collections

Also we have another Set that contains, Sia and Andrew.


	var y = mutableSetOf("Sia", "Andrew")
java_Collections


Next, we have used the addAll() function to add the new Set y that contains Sia and Andrew at the end of the Set x.


x.addAll(y)

And the Set y is joined with x.

java_Collections

And we get the below output,


[Mohan, Kriti, Salim, Sia, Andrew]