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?
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.
once
contains {2,4,6,8,9} and twice
is empty.once
set, so they are added to the twice
set.once
is now {2,4,6,8,9}, twice
is now {2,8,9}.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).twice
from once
. once
is now {6}. Return once
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With