Sets
A Set keeps unique elements. Adding a value already present leaves the set unchanged.
HashSet favors general lookup speed without promising iteration order. LinkedHashSet also remembers insertion order, which makes displayed results predictable.
Keep each value once
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<Integer> scanned = new HashSet<>();
System.out.println(scanned.add(42));
System.out.println(scanned.add(42));
System.out.println(scanned.size());
System.out.println(scanned.contains(42));
}
}
Output:
true
false
1
true
The first add succeeds. The second returns false because 42 is already present, and the set still has one element. contains reports whether a value is in the set.
Keep insertion order
import java.util.LinkedHashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<String> tags = new LinkedHashSet<>();
tags.add("travel");
tags.add("food");
tags.add("travel");
tags.add("art");
System.out.println(tags);
}
}
Output:
[travel, food, art]
The second "travel" is ignored, and the remaining tags print in the order they were first added. Printing a set shows its elements in square brackets.
Uniqueness follows equals and hashCode. Broken equality methods produce broken set behavior.
Keep each guest once in arrival order, then check whether Maya is present.