08 Handout 1
08 Handout 1
Sets
• A set is a collection of elements where each element is
unique.
• Common set operations:
o Union: The union of two (2) sets (A ∪ B) is the set that
contains all the elements in either set.
Example: {1, 3, 5, 7} ∪ {2, 3, 4, 5} = {1, 2, 3, 4, 5, 7}
o Intersection: The intersection of two (2) sets (A ∩ B)
is the set that contains only the elements common to
both sets.
Example: {1, 3, 5, 7} ∩ {2, 3, 4, 5} = {3, 5} Output:
o Difference: The difference of sets A and B (A – B) is Union: [Marco, Nika, Mairo, John, Mark, Kae]
the set that contains the elements that are in A but not Intersection: [Mark]
in B. Difference: [Nika, Mairo, Kae]
Example: {1, 3, 5, 7} – { 2, 3, 4, 5} = {1, 7} 4. To determine whether a set is a subset of another set:
o Subset: Set A is a subset of set B (A ⊂ B) if every System.out.println(a.containsAll(b));
element of set A is also an element of set B. • Curly braces or the set() function can be used to implement
Example: {1, 3, 5, 7} ⊂ {1, 2, 3, 4, 5, 7} = true sets in Python.
• Java contains three (3) general-purpose set implementations. • Sample codes for sets in Python:
All are included in the java.util package. 1. To create an empty set:
o HashSet – This stores its elements in a hash table a = set()
without a guaranteed order upon iteration. This is the 2. To initialize a set:
best-performing implementation. a = set(["Mark", "Nika", "Mairo", "Kae"])
o TreeSet – This stores its elements in a special type b = {"John", "Marco", "Mark"}
of tree where elements are sorted (natural or custom) #Equivalent to multiple use of add()
during iteration. 3. To determine the union, intersection, and difference:
o LinkedHashSet – This stores its elements in a hash
table with a linked list running through it. The order of
the elements during the iteration is the same as the
order they were inserted into the set.
• Sample codes for sets in Java:
1. To create an empty set:
Set a = new HashSet(); 4. To determine whether a set is a subset of another set:
Set b = new TreeSet (); print(a.issubset(b))
Set c = new LinkedHashSet();
2. To add items to the set:
Collections.addAll(a, "Mark", "Nika", "Mairo", "Kae");
//equivalent to multiple use of add()