Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

HashSet

A set without duplicates backed by a hash table; order is not guaranteed.

Available since: Java 1.2

Syntax

public class HashSet<E> implements Set<E>

Examples

Duplicates are dropped automatically:

void main() {
    Set<String> tags = new HashSet<>();
    tags.add("java");
    tags.add("sql");
    tags.add("java");
    IO.println(tags.size());
    IO.println(tags.contains("sql"));
}

Output:

2
true

The unique words of a text:

void main() {
    String text = "to be or not to be";
    Set<String> words = new HashSet<>(List.of(text.split(" ")));
    IO.println(words.size() + " unique words");
}

Output:

4 unique words

Notes

add(), contains() and remove() run in constant time regardless of size. The iteration order depends on hashes and differs from the insertion order — do not rely on it. Your own classes need correct equals() and hashCode(); records get them automatically.

See also

  • LinkedHashSet — A set that remembers the insertion order of elements.
  • TreeSet — A set that keeps its elements in sorted order.
  • Set.add() — Adds an element if it is not in the set yet.
  • Set.contains() — Checks whether a set contains an element.

Related recipes

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.