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).
List<String> names = List.of("Ann", "Bob"); Stream<String> s = names.stream();
Try it
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.
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
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 throwsConcurrentModificationExceptionor gives undefined results. - No copy is made. The stream reads the collection directly, so streaming is O(1) to create.
- Order: a
HashSetorHashMapstream has no meaningful order. Sort, or useLinkedHashMap/TreeMapwhen order matters. parallelStream()is juststream().parallel()for collections. Do not default to it; see parallel streams.- Null collections: calling
stream()onnullthrowsNullPointerException. Return empty collections rather thannullfrom methods. - Iterable only: an
Iterablethat is not aCollectionhas nostream(); wrap itsspliterator()withStreamSupport.stream(it.spliterator(), false). - Java 16+:
Stream.toList()is a shorter way to get a list at the end.