Search code examples
javajava-8java-stream

What is the difference between .stream() and Stream.of?


Which is the best way to create a stream out of a collection:

    final Collection<String> entities = someService.getArrayList();
  1. entities.stream();

  2. Stream.of(entities);


Solution

  • The second one does not do what you think it does! It does not give you a stream with the elements of the collection; instead, it will give you a stream with a single element, which is the collection itself (not its elements).

    If you need to have a stream containing the elements of the collection, then you must use entities.stream().