import java.util.*;
public class SetOfIntegers {
    public static void arrayToSet(int[] array, Set set) {
        for (int n : array) {
            set.add(n);
        }
    }
    public static HashSet intersection(HashSet<Integer> setA, HashSet<Integer> setB) {
        HashSet<Integer> setR = new HashSet<>();
        for(Integer n: setA) {
            if (setB.contains(n)) {
                setR.add(n);
            }
        }
        return setR;
    }
    public static HashSet union(HashSet<Integer> setA, HashSet<Integer> setB) {
        HashSet<Integer> setR;
        setR = (HashSet)setA.clone(); // Casting necesario porque clone()
            // es de HashSet pero overrides el method de Object
            // Returns a shallow copy the elements themselves are not cloned.
        for(Integer n: setB) {
            //if (!setR.contains(n)) {
            setR.add(n); // si ya esta no lo vuelve a añadir
            // }
        }
        return setR;
    }
    public static HashSet subtraction(HashSet<Integer> setA, HashSet<Integer> setB) {
        HashSet<Integer> setR;
        setR = (HashSet)setA.clone();
        setR.removeAll(setB);
        return setR;
    }
    public static HashSet symmetricDifference(HashSet<Integer> setA, HashSet<Integer> setB) {
        HashSet<Integer> setR;
        // The symmetric difference is the union minus the intersection.
        setR = subtraction(union(setA,setB), intersection(setA,setB));
        return setR;
    }
    public static void main(String args[]) {
        int[] arrayA = {3, 2, 1, 6, 7};
        int[] arrayB = {2, 4, 0, -1, -3};
        HashSet<Integer> a = new HashSet<>();
        HashSet<Integer> b = new HashSet<>();
        arrayToSet(arrayA, a);
        arrayToSet(arrayB, b);
        System.out.println("A: " + a);
        System.out.println("B: " + b);
        System.out.println("Intersection A y B:   " + intersection(a, b));
        System.out.println("Union A y B       :   " + union(a, b));
        System.out.println("Substraction A - B:   " + subtraction(a, b));
        System.out.println("Symmetric difference: " + symmetricDifference(a, b));
        TreeSet sortedA = new TreeSet<>(a);
        TreeSet sortedB = new TreeSet<>(b);
        System.out.println("The sorted sets are:");
        System.out.println("A: " + sortedA);
        System.out.println("B: " + sortedB);
        System.out.println("The First element of the sorted set A is: "
                + (Integer) sortedA.first());
        System.out.println("The last element of the sorted set A is: "
                + (Integer) sortedA.last());
        //
        HashSet<Integer> c = new HashSet<>();
        for(int i=-100; i<=100; i++) {
            c.add(i);
        }
         System.out.println("C: " + c);
         TreeSet sortedC = new TreeSet<>(c);
         System.out.println("C: " + sortedC);
         //
    }
}
