Java Stream How to - Convert Stream to Set








Question

We would like to know how to convert Stream to Set.

Answer

/*from w  w  w.jav a  2s . c om*/
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    // collect as typed array
    Stream<String> words = Stream.of("All", "men", "are", "created", "equal");
    Set<String> wordsSet = words.collect(Collectors.toSet());
    wordsSet.forEach(n -> System.out.println(n));
  }
}

The code above generates the following result.