Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Streams and Functional

Java Collection.stream() method

Reference for Collection.stream() and parallelStream(): create streams from lists, sets and map views, and learn how ordering and late binding work.

Collection.stream() is a default method that returns a sequential stream whose source is the collection. Every List, Set and Queue has it. parallelStream() returns a stream that may process elements on several threads.

A Map is not a Collection, so it has no stream(); stream one of its views instead: entrySet(), keySet() or values(). Arrays use Arrays.stream(array).

Java
List<String> names = List.of("Ann", "Bob");
Stream<String> s = names.stream();

Try it

Java Streaming lists, sets and maps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java The stream sees the list when it runs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
default Stream<E> stream()
default Stream<E> parallelStream()

Returns: a stream over the elements. It reports ORDERED when the collection has an encounter order (lists, LinkedHashSet, TreeSet) and SIZED for most standard collections, which lets count() and toList() skip work.

Usage notes

  • Late binding: most collections bind to their data when the terminal operation starts, not when stream() is called. Changes between the two are seen (see the second example). Changing the source while the pipeline runs usually throws ConcurrentModificationException or gives undefined results.
  • No copy is made. The stream reads the collection directly, so streaming is O(1) to create.
  • Order: a HashSet or HashMap stream has no meaningful order. Sort, or use LinkedHashMap/TreeMap when order matters.
  • parallelStream() is just stream().parallel() for collections. Do not default to it; see parallel streams.
  • Null collections: calling stream() on null throws NullPointerException. Return empty collections rather than null from methods.
  • Iterable only: an Iterable that is not a Collection has no stream(); wrap its spliterator() with StreamSupport.stream(it.spliterator(), false).
  • Java 16+: Stream.toList() is a shorter way to get a list at the end.