-6

Have 2 sets with duplicates set1 ={1,2,3,4,5} set2 = {1,3,6,7} and the result should be set3 ={2,4,5,6,7} Please let me reiterate that I want to use Set interface and the result set should be ordered natural.

  • So what have you tried so far? Have you looked at the `Set` interface? – Jon Skeet Jun 09 '15 at 09:10
  • Yes, looked at this was an interview question. – user_falafel Jun 09 '15 at 09:12
  • 1
    [this](http://stackoverflow.com/questions/5868808/api-for-set-operations-in-java) [has](http://stackoverflow.com/questions/3590677/how-to-union-intersect-difference-and-reverse-data-in-java) [been](http://stackoverflow.com/questions/15575417/how-to-remove-common-values-from-two-array-list) [asked](http://stackoverflow.com/questions/5943330/common-elements-in-two-lists) [before](http://stackoverflow.com/questions/9917787/merging-two-arraylists-into-a-new-arraylist-with-no-duplicates-and-in-order-in). We want to help people out, but please check google before posting a question :) – John M Jun 09 '15 at 09:13
  • I don't see how "looked at this was an interview question" answers my question at all... – Jon Skeet Jun 09 '15 at 09:19

2 Answers2

2
  • Find the intersection
  • Find the union
  • Subtract the intersection from the union

Code:

 public static void main(String[] args) {

    Set<Integer> set1 = new HashSet<Integer>(Arrays.asList(1, 2, 3, 4, 5));
    Set<Integer> set2 = new HashSet<Integer>(Arrays.asList(1, 3, 6, 7));

    Set<Integer> intersection = new HashSet<Integer>(set1);
    intersection.retainAll(set2);

    // set1 is now the union of set1 and set2
    set1.addAll(set2);

    // set1 is now (union - intersection)
    // All elements in set1 or set2, but not in both set1 & set2
    set1.removeAll(intersection);

    for(Integer n : set1) {
        System.out.println(n);
    }
}

Output:

2
4
5
6
7
almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
1

You may try this -

Set set1, set2;
Set newSet = new HashSet(set1);
newSet.addAll(set2);
k.shamsu
  • 69
  • 8