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




difference( ) FUNCTION


The 'difference( )' Function is used to find the difference between two Sets. Let us understand it with the below example.


Say for example, we have a Set that contains three names, 'Mohan', 'Kriti' and 'Salim'.


And we have a second 'Set' that contains three names 'Sia', 'Andrew' and 'Kriti'.


Let us see the 'difference( )' Function first.


Example :


x = {"Mohan", "Kriti", "Salim"}
y = {"Sia", "Andrew", "Kriti"}
z = x.difference(y)
print(z) 


Output :



  {'Salim', 'Mohan'}

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


x = {"Mohan", "Kriti", "Salim"}

java_Collections

Then what we have done is, put the names, 'Sia', 'Andrew' and 'Kriti' in another set 'y'.


y = {"Sia", "Andrew", "Kriti"}

java_Collections

Then we have used the 'difference( )' Function.


z = x.difference(y)

The 'difference( )' Function will only take the values of x i.e. 'Mohan', 'Kriti' and 'Salim'.Then goto the set 'y' and try finding the common element in both the Sets.


And since, 'Kriti' is present in both the Sets, 'Kriti' will be discarded.


And just, 'Mohan' and 'Salim' would be put into the new Set.


java_Collections

And we get the below output,


{'Salim', 'Mohan'}