A bag of unique things
A set stores values with no duplicates. Adding something that's already there does nothing:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> visited = new HashSet<>();
System.out.println(visited.add("Goa"));
System.out.println(visited.add("Kerala"));
System.out.println(visited.add("Goa"));
System.out.println("Places: " + visited.size());
System.out.println(visited.contains("Kerala"));
}
}Output
true true false Places: 2 true
add returns false when the value was already in the set.
Think of it like this: A guest list at a party: each name is written once, no matter how many times someone says it.
Removing duplicates, sorted
A TreeSet is a set that keeps its values sorted:
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
int[] rolls = {4, 2, 6, 2, 4, 1, 6, 6};
TreeSet<Integer> unique = new TreeSet<>();
for (int r : rolls) {
unique.add(r);
}
System.out.println(unique);
System.out.println("Smallest: " + unique.first() + ", largest: " + unique.last());
}
}Output
[1, 2, 4, 6] Smallest: 1, largest: 6
Which collection should I use?
| You need... | Use |
|---|---|
| an ordered list, duplicates OK, access by position | ArrayList |
| to look up a value by a key | HashMap (or TreeMap for sorted keys) |
| unique values, fast “is it there?” checks | HashSet (or TreeSet for sorted) |