Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Set.contains()

Checks whether a set contains an element.

Available since: Java 1.2

Syntax

boolean contains(Object o)

Parameters

ParameterTypeDescription
oObjectThe 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
world

Notes

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

In the tutorial

  • Sets: Set — Sets in Java: HashSet without duplicates, LinkedHashSet and TreeSet with ordering, union and intersection of sets.

Thanks for reading!

Donate to the site — we work hard for you.