Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Collectors.toSet()

A collector that puts stream elements into a set without duplicates.

Available since: Java 8

Syntax

static <T> Collector<T, ?, Set<T>> toSet()

Return value

Collector<T, ?, Set<T>>A collector into a set.

Examples

Unique email domains:

void main() {
    Set<String> domains = Stream.of("a@x.com", "b@y.org", "c@x.com")
        .map(e -> e.substring(e.indexOf('@') + 1))
        .collect(Collectors.toSet());
    IO.println(domains.size());
    IO.println(domains.contains("y.org"));
}

Output:

2
true

Notes

The order of elements is not guaranteed. For a sorted result gather into a TreeSet: Collectors.toCollection(TreeSet::new). Collectors.toUnmodifiableSet() gives an unmodifiable set.

See also

  • Collectors.toList() — A collector that puts stream elements into a list.
  • Stream.distinct() — Removes duplicate elements from a stream.
  • HashSet — A set without duplicates backed by a hash table; order is not guaranteed.

In the tutorial

  • Collectors — The collect method and the Collectors class — toList, toSet, toMap, joining, counting, summingInt, averagingDouble and the duplicate key error.

Thanks for reading!

Donate to the site — we work hard for you.