Collectors toSet() example

Description

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  ww.  ja  va  2  s.c  om
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.





















Home »
  Java Streams »
    Reference »




Collectors
DoubleStream
DoubleStream.Builder
IntStream
IntStream.Builder
LongStream
LongStream.Builder
Stream
Stream.Builder