Sunday 26 February 2012

Set operations: union, intersection, difference, symmetric difference, is subset, is superset - using TreeSet in Java

The mathematical set operations using Java Collection-Framework  is given below

import java.util.TreeSet;
import java.util.Set;
import java.util.TreeSet;

public class Main {
  public static  Set union(Set setA, Set setB) {
    Set tmp = new TreeSet(setA);
    tmp.addAll(setB);
    return tmp;
  }

  public static  Set intersection(Set setA, Set setB) {
    Set tmp = new TreeSet(setA);
   tmp.retainAll(setB);
    return tmp;
  }
  public static  Set difference(Set setA, Set setB) {
    Set tmp = new TreeSet(setA);
    tmp.removeAll(setB);
    return tmp;
  }

  public static  Set symDifference(Set setA, Set setB) {
    Set tmpA;
    Set tmpB;

    tmpA = union(setA, setB);
    tmpB = intersection(setA, setB);
    return difference(tmpA, tmpB);
  }

  public static  boolean isSubset(Set setA, Set setB) {
    return setB.containsAll(setA);
  }

  public static  boolean isSuperset(Set setA, Set setB) {
    return setA.containsAll(setB);
  }

  public static void main(String args[]) {
    TreeSet set1 = new TreeSet();
    TreeSet set2 = new TreeSet();

    set1.add('A');
    set1.add('B');
    set1.add('C');
    set1.add('D');

    set2.add('C');
    set2.add('D');
    set2.add('E');
    set2.add('F');

    System.out.println("set1: " + set1);
    System.out.println("set2: " + set2);

    System.out.println("Union: " + union(set1, set2));
    System.out.println("Intersection: " + intersection(set1, set2));
    System.out.println("Difference (set1 - set2): " + difference(set1, set2));
    System.out.println("Symmetric Difference: " + symDifference(set1, set2));

    TreeSet set3 = new TreeSet(set1);

    set3.remove('D');
    System.out.println("set3: " + set3);

    System.out.println("Is set1 a subset of set3? " + isSubset(set1, set3));
    System.out.println("Is set1 a superset of set3? " + isSuperset(set1, set3));
    System.out.println("Is set3 a subset of set1? " + isSubset(set3, set1));
    System.out.println("Is set3 a superset of set1? " + isSuperset(set3, set1));

  }
}

The output is

set1: [A, B, C, D]
set2: [C, D, E, F]
Union: [A, B, C, D, E, F]
Intersection: [C, D]
Difference (set1 - set2): [A, B]
Symmetric Difference: [A, B, E, F]
set3: [A, B, C]
Is set1 a subset of set3? false
Is set1 a superset of set3? true
Is set3 a subset of set1? true
Is set3 a superset of set1? false  

No comments:

Post a Comment