Java Streams - Collectors toSet() example








Collectors toSet() returns a Collector that accumulates the input elements into a new Set.

Syntax

toSet has the following syntax.

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

Example

The following example shows how to use toSet.

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/*from w w  w  . j a  va  2  s  .co  m*/
public class Main {
  public static void main(String[] args) {
    Stream<String> s = Stream.of("a","b","c");
    
    Set<String> names = s
        .collect(Collectors.toSet());

    System.out.println(names);
  }
}

The code above generates the following result.