Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save rmg007/61ed3829c3095733be720d861a8e380b to your computer and use it in GitHub Desktop.

Select an option

Save rmg007/61ed3829c3095733be720d861a8e380b to your computer and use it in GitHub Desktop.
set operations using containsAll addAll removeAll retainAll
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class CollectionInterfaceMethodsToPerformSetOperations {
static Collection<Integer> firstSet = new HashSet<>(Set.of(1, 2, 3, 4, 5, 6));
static Collection<Integer> secondSet = new HashSet<>(Set.of(4, 5, 6, 7, 8, 9));
static Collection<Integer> smallSet = new HashSet<>(Set.of(1, 2, 3));
public static void subSet(){
boolean isSubSet = firstSet.containsAll(smallSet);
System.out.println(isSubSet);
}
public static void union() {
firstSet.addAll(secondSet);
}
public static void intersection(){
firstSet.retainAll(secondSet);
}
public static void difference(){
secondSet.removeAll(firstSet);
}
public static void main(String[] args) {
//subSet();
//union();
//intersection();
difference();
System.out.println(secondSet);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment