patternjavaModerate
Find the uncommon elements from two sets
Viewed 0 times
theelementsuncommonsetstwofindfrom
Problem
I am trying to find the uncommon elements from two sets in Java. Here is my way:
I have declared two extra sets. Can this be improved?
private void findUnCommon{
Set a = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set b = new HashSet<>(Arrays.asList(3, 4, 5, 6));
// get all elements from set a and set b
System.out.println("Before..");
System.out.println("a is : " + a);
System.out.println("b is : " + b);
Set result = new HashSet<>(a);
result.removeAll(b);
System.out.println("result is : " + result);
Set temp = new HashSet<>(b);
temp.removeAll(a);
System.out.println("temp is : " + temp);
result.addAll(temp);
System.out.println("Uncommon elements of set a and set b is : "
+ result);
System.out.println("After..");
System.out.println("a is : " + a);
System.out.println("b is : " + b);
}I have declared two extra sets. Can this be improved?
Solution
Is this a method? You can't just plop code anywhere in Java.
The name of the operation is symmetric difference, so you should probably call it that.
Here's a more compact implementation.
The name of the operation is symmetric difference, so you should probably call it that.
Here's a more compact implementation.
private Set symmetricDifference(Set a, Set b) {
Set result = new HashSet(a);
for (T element : b) {
// .add() returns false if element already exists
if (!result.add(element)) {
result.remove(element);
}
}
return result;
}Code Snippets
private Set<T> symmetricDifference(Set<T> a, Set<T> b) {
Set<T> result = new HashSet<T>(a);
for (T element : b) {
// .add() returns false if element already exists
if (!result.add(element)) {
result.remove(element);
}
}
return result;
}Context
StackExchange Code Review Q#32297, answer score: 10
Revisions (0)
No revisions yet.