4

I have written a program with 2 different collections of numbers and I was wondering how would I get the union, intersection and set difference from these two collections? I know that BitSet has methods for it but those doesn't work here.

public class Collections {

public static void main(String[] args) {

    // 1. Collection
    Set<Integer> grp1 = new HashSet<Integer>();

    grp1.add(1);
    grp1.add(2);
    grp1.add(3);
    grp1.add(4);
    grp1.add(5);

    // printing 1. collection
    System.out.println("1. collection: ");
    Iterator<Integer> i = grp1.iterator();
    while(i.hasNext()) {
        int numbers1 = i.next();
        System.out.print(numbers1 + " ");
    }
    System.out.println();   

    // 2. collection
    Set<Integer> grp2 = new HashSet<Integer>();

    grp2.add(8);
    grp2.add(7);
    grp2.add(6);
    grp2.add(5);
    grp2.add(4);

    // printing 2. collection
    System.out.println("2. collection: ");
    Iterator<Integer> y = grp2.iterator();
    while(y.hasNext()) {
        int numbers2 = y.next();
        System.out.print(numbers2 + " ");

    // Union


    // Intersection


    // Difference

         }
     }

}
Daniel
  • 89
  • 1
  • 2
  • 8

2 Answers2

12

Union:

Set<Integer> union = new HashSet<>(grp1);
union.addAll(grp2);

Intersection:

Set<Integer> intersection = new HashSet<>(grp1);
intersection.retainAll(grp2);

Difference:

Set<Integer> diff = new HashSet<>(grp1);
diff.removeAll(grp2);
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • I wish it worked that way, but all of those operations are actually destructive, i.e. they work in-place, on the existing collection, and they all return boolean. Your code does unfortunately not compile. I wish it did. – Sean Patrick Floyd Aug 04 '16 at 13:54
  • I already did try those but none of them work in Eclipse:'' Type mismatch: cannot convert from boolean to Set''. EDIT: like Sean said they return boolean values. – Daniel Aug 04 '16 at 14:01
  • Ah true!! I forgot about the signatures! Too much scala those days :) – Jean Logeart Aug 04 '16 at 14:21
7

Guava has these operations in it's Sets class.

Set<Integer> union = Sets.union(set1, set2);
Set<Integer> intersection = Sets.intersection(set1, set2);
Set<Integer> difference = Sets.difference(set1, set2);

All of these return unmodifiable views, backed by the original Sets.

See Guava Explained -> Collection Utilities -> Sets

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588