Sets difference() function | Guava | Java
Last Updated :
15 Nov, 2018
Guava’s Sets.difference() returns an unmodifiable view of the difference of two sets.
Syntax:
public static <E>
Sets.SetView<E>
difference(Set<E> set1,
Set<?> set2)
Return Value: This method returns a set containing all elements that are contained by set1 and not contained by set2.
Note: Set2 may also contain elements not present in set1, these are simply ignored. The iteration order of the returned set matches that of set1.
Example 1:
import com.google.common.collect.Sets;
import java.util.Set;
class GFG {
public static void main(String[] args)
{
Set<Integer>
set1 = Sets.newHashSet( 1 , 2 , 3 , 4 , 5 , 6 );
Set<Integer>
set2 = Sets.newHashSet( 1 , 3 , 5 , 7 );
Set<Integer>
diff = Sets.difference(set1, set2);
System.out.println( "Set 1: "
+ set1);
System.out.println( "Set 2: "
+ set2);
System.out.println( "Difference between "
+ "Set 1 and Set 2: "
+ diff);
}
}
|
Output:
Set 1: [1, 2, 3, 4, 5, 6]
Set 2: [1, 3, 5, 7]
Difference between Set 1 and Set 2: [2, 4, 6]
Example 2 :
import com.google.common.collect.Sets;
import java.util.Set;
class GFG {
public static void main(String[] args)
{
Set<String>
set1 = Sets
.newHashSet( "H" , "E" , "L" , "L" , "O" , "G" );
Set<String>
set2 = Sets
.newHashSet( "L" , "I" , "K" , "E" , "G" );
Set<String>
diff = Sets.difference(set1, set2);
System.out.println( "Set 1: "
+ set1);
System.out.println( "Set 2: "
+ set2);
System.out.println( "Difference between "
+ "Set 1 and Set 2: "
+ diff);
}
}
|
Output:
Set 1: [E, G, H, L, O]
Set 2: [I, K, L, E, G]
Difference between Set 1 and Set 2: [H, O]
Share your thoughts in the comments
Please Login to comment...