Java Using Sets v1
Java Using Sets v1
COLLECTION
•add()
•remove()
•size()
•contains()
•clear()
•isEmpty()
•… and more!
Types of Collections
COLLECTION INTERFACE
LIST SET
COLLECTION INTERFACE
LIST SET
0 1 2 3 4 5 6 7 8
A Set
SETS
•TreeSet
•EnumSet
Initializing a Set
Our Set will store the names of some programming languages as
Strings.
Set<String>
Set String languages = new HashSet<>();
HashSet<>
Why not make the variable a HashSet on the left instead of Set?
Set of Integers
Set<Integer> numbers = new HashSet<>();
System.out.println(languages.size());
Console output
> 3
Adding Elements to a Set - NO Duplicates
Set<String> languages = new HashSet<>(Arrays.asList("HTML","CSS","JS"));
languages.add("HTML");
languages.add("CSS");
System.out.println(languages.size());
Console output
> 3
HTML
CSS
JS
A Review of General Set Operations
We have 2 sets: 1 for front end languages and 1 for back end.
Java
HTML
JS JS Ruby
CSS
C#
Set Operations - Intersection
What languages are in both the front end set AND the back
end set?
Front End Back End
In Java, a Set's retainAll()
method returns the intersection
of two Sets Java
HTML
JS Ruby
CSS
C#
Set Operations - Intersection (retainAll)
Set<String> frontEnd = new HashSet<>(Arrays.asList("HTML","CSS","JS"));
Console output
The only value that is
> JS "retained" because it exists
in both groups is JS
Set Operations - Union
What languages are in either the front end set AND the back
end set?
Front End Back End
In Java, a Set's addAll()
method returns the union of
two Sets
HTML Java
JS Ruby
CSS
C#
Set Operations - Union (addAll)
Set<String> frontEnd = new HashSet<>(Arrays.asList("HTML","CSS","JS"));
Set<String> backEnd = new HashSet<>(Arrays.asList("Java","C#","Ruby","JS"));
Console output
> HTML
CSS Notice JS only appears once
JS even though it was added
again with the frontend values.
Java
Ruby
C#
Set Operations - Subtraction (remove)
Set<String> frontEnd = new HashSet<>(Arrays.asList("HTML","CSS","JS"));
frontEnd.remove("JS");
Console output
> HTML
CSS
HTML
_ HTML
CSS
JS JS
= CSS
Console output
Java
> HTML
CSS
HTML Java
_ HTML
CSS JS Ruby
C#
JS
C#
Ruby
= CSS
Console output
> CSS Elements are added in sorted
order to the TreeSet
HTML
Java
JavaScript
Ruby
Why can't we just use a
List?
An Unsorted List with Unique Values
vs a Set
String[] languages = {"Java", "C#", "Go"};
String[] moreLanguages = {"Java", "C#", "JavaScript", "Python"};