Set.contains()
Checks whether a set contains an element.
Available since: Java 1.2
Syntax
boolean contains(Object o)Parameters
| Parameter | Type | Description |
|---|---|---|
| o | Object | The element to look for. |
Return value
boolean`true` if the element is in the set.
Examples
Filtering by a block list:
void main() {
Set<String> banned = Set.of("spam", "ads");
List<String> words = List.of("hello", "spam", "world", "ads");
for (String w : words) {
if (!banned.contains(w)) {
IO.println(w);
}
}
}Output:
hello
worldNotes
On a HashSet the check runs in constant time and on a TreeSet in logarithmic time, while a list's contains() scans every element. So if you need many checks, put the data into a set first.
See also
- Set.add() — Adds an element if it is not in the set yet.
- List.contains() — Checks whether a list contains an element.
- Map.containsKey() — Checks whether a map has a key.
In the tutorial
- Sets: Set — Sets in Java: HashSet without duplicates, LinkedHashSet and TreeSet with ordering, union and intersection of sets.