Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all the elements which has no duplicate in multiple HashSet of Integers in Java

Tags:

java

set

In multiple HashSet of Integers I want to get all those elements, which has no duplicate. i.e. which came only once in union of all the HashSet. I am not able to conceptualize it programmatically.

As an example, consider set first contains {2,4,6,8,9}, second set contains {2,8,9} and third set contains {2,4,8,9}. In all these set, element 6 occurs only once.

How to find all the elements which has no duplicate in multiple HashSet of Integers in Java?

like image 789
Ravi Joshi Avatar asked Dec 08 '12 14:12

Ravi Joshi


1 Answers

You could hold the set of elements that occur at least once and at least twice. It's a bit of manual looping but it's possible. This will work for any number of sets to difference and will not modify the input:

public static Set<E> unique(Set<? extends E>... sets){
   Set<E> once = new HashSet<E>();
   Set<E> twice = new HashSet<E>();

   for(Set<? extends E> set:sets){
      for(E el:set){
         if(once.contains(el)){
            twice.add(el);
         } else {
            once.add(el);
         }
      }
   }

   once.removeAll(twice);
   return once;
} 

Ideone: http://ideone.com/reGDBy

Example usage:

Set<Integer> set1, set2, set3;
...
Set<Integer> u = unique(set1, set2, set3);

Example of evaluation:

As an example, consider set first contains {2,4,6,8,9}, second set contains {2,8,9} and third set contains {2,4,8,9}. In all these set, element 6 occurs only once.

  • After the first inner loop completes, once contains {2,4,6,8,9} and twice is empty.
  • Adding the second set: 2, 8 and 9 are already in the once set, so they are added to the twice set.
  • once is now {2,4,6,8,9}, twice is now {2,8,9}.
  • From the third set: 2 is re-added to twice, 4 is added to twice, 8, 9 are re-added to twice.
  • once is now {2,4,6,8,9} (union of all sets), twice is now {2,4,8,9} (elements that occur at least twice).
  • remove twice from once. once is now {6}. Return once.
like image 151
John Dvorak Avatar answered Sep 29 '22 06:09

John Dvorak