Java - Set union, intersection, difference and subset

Introduction

Set supports the union, intersection, and difference operations.

// Union of s1 and s2 will be stored in s1
s1.add(s2);

// Intersection of s1 and s2 will be stored in s1
s1.retainAll(s2);

// Difference of s1 and s2 will be stored in s1
s1.removeAll(s2);

During the set operations such as union, intersection, and difference, the set on which you perform the operation is modified.

s1 is modified if you perform s1.addAll(s2) to compute the union of s1 and s2.

To compute the union of two sets and keep the original set unchanged, make a copy of the original set before you perform the union operation.

// Compute the union of two sets by keeping the original set unchanged
Set s1Unions2 = new HashSet(s1); // Make a copy of s1

// Now, s1Unions2 is the union of s1 and s2 and both s1 and s2 are unchanged
s1Unions2.addAll(s2);

You can use the s2.containsAll(s1) method to test if s1 is a subset of s2.

Demo

import java.util.HashSet;
import java.util.Set;

public class Main {
  public static void main(String[] args) {
    // Create a set
    Set<String> s1 = new HashSet<>();
    s1.add("XML");
    s1.add("Json");
    s1.add("Java");

    // Create another set
    Set<String> s2 = new HashSet<>();
    s2.add("Python");
    s2.add("Ruby");
    s2.add("Json");

    // Print the elements of both sets
    System.out.println("s1: " + s1);
    System.out.println("s2: " + s2);

    // Perform set operations
    performUnion(s1, s2);/* w  ww  .  j  av a 2  s . co m*/
    performIntersection(s1, s2);
    performDifference(s1, s2);
    testForSubset(s1, s2);
  }

  public static void performUnion(Set<String> s1, Set<String> s2) {
    Set<String> s1Unions2 = new HashSet<>(s1);
    s1Unions2.addAll(s2);
    System.out.println("s1 union s2: " + s1Unions2);
  }

  public static void performIntersection(Set<String> s1, Set<String> s2) {
    Set<String> s1Intersections2 = new HashSet<>(s1);
    s1Intersections2.retainAll(s2);
    System.out.println("s1 intersection s2: " + s1Intersections2);
  }

  public static void performDifference(Set<String> s1, Set<String> s2) {
    Set<String> s1Differences2 = new HashSet<>(s1);
    s1Differences2.removeAll(s2);

    Set<String> s2Differences1 = new HashSet<>(s2);
    s2Differences1.removeAll(s1);

    System.out.println("s1 difference s2: " + s1Differences2);
    System.out.println("s2 difference s1: " + s2Differences1);
  }

  public static void testForSubset(Set<String> s1, Set<String> s2) {
    System.out.println("s2 is subset s1: " + s1.containsAll(s2));
    System.out.println("s1 is subset s2: " + s2.containsAll(s1));
  }
}

Result