...

/

Symmetric Difference and Propositional Logic

Symmetric Difference and Propositional Logic

Learn how to use symmetric difference with propositional logic in programming.

Introduction to symmetric difference

The very conception of symmetric difference doesn’t exist without the set abstraction. Based on that, we can quickly implement that abstraction in our Java code. In general, the symmetric difference between two sets means a new set, where duplication is nonexistent.

Press + to interact
import java.util.HashSet;
import java.util.Set;
class Main{
public static void main(String[] args) {
Set<String> uniqueSet = new HashSet<String>();
Set<String> duplicateSet = new HashSet<String>();
String[] ourArguments = {"I", "saw", "Mary", "I", "left", "Mary", "stayed"};
for (String a : ourArguments){
if (!uniqueSet.add(a)){
duplicateSet.add(a);
}
}
System.out.println("Applying the symmetric difference abstraction : ");
uniqueSet.removeAll(duplicateSet);
System.out.println("Unique words in a unique set: " + uniqueSet);
System.out.println("Duplicate words in a unique set: " + duplicateSet);
}
}

What kind of output can we expect here? The arguments we pass possess unique words, as well as duplicate words. We try to identify both the unique words and the duplicate words. After that, we produce them in the following output.

Applying the symmetric difference abstraction : 
Unique words in a unique set:    [left, stayed, saw]
Duplicate words in a unique set: [I, Mary]

The power of this code lies in the use of Java’s HashSet<>, which doesn’t allow duplicate entries.

  • Line 12: If we ...