Java has two different types of sets, Unsorted and Sorted… even if Math Sets are technically unsorted.
Unsorted Sets
Unsorted sets in Java are not a class that can be defined. Therefore you need to use the HashSet and then use the polymorphic nature of the OOP to create the set.
Set<Integer> set1 = new HashSet<Integer>();
From here, you want to add elements to the set. You can add a single element, or a list of elements.
// add a single element
set1.add(5);
// add a list of elements
set1.addAll(Arrays.asList(new Integer[] { 2, 4, 6, 8, 8, 10 }));
If you add an element that already exists, it will be ignored just as with a regular set.
There are three common events that you will perform with a set: Union, Intersection, and Difference.
Union
Instead of the union command, you will use the addAll method, passing in a second set. Notice that this will update the set.
// duplicate a set
Set<Integer> union = new HashSet<Integer>(set1);
// create a union
union.addAll(set2);
Intersection
The intersection uses a different method name, retainAll().
// duplicate a set
Set<Integer> intersection = new HashSet<Integer>(set1);
// create the intersection
intersection.retainAll(set2);
Difference
For difference, you use the removeAll method.
// duplicate a set
Set<Integer> difference = new HashSet<Integer>(set1);
// creating the difference
difference.removeAll(set2);
Sorted Sets
For a sorted set, you need to create a TreeSet
.
SortedSet<String> ts = new TreeSet<string>();
If you want to use something that is a custom class, you will need to create a comparator object. This is assuming you are using a Product
class. Of course, you will want to change it to what ever you work with.
Comparator<Product> comparator =
Comparator.comparingDouble(Product::getPrice).reversed();
SortedSet<Product> ts = new TreeSet<Product>(comparator);
The same three main methods you have with an unsorted set Union, Intersection, and Difference.
Java Sets was originally found on Access 2 Learn