liveBook · Manning

Stream.of

As explained in 100 Java Mistakes and How to Avoid Them

Stream.of is a Java factory method that creates a Stream from supplied elements.

Stream.of creates a stream from supplied elements. A common mistake is using Stream.of(list) when the intended stream should contain the list’s elements; use list.stream() for a collection. section 8.2

The collection-is-one-element mistake

Incorrect: Stream.of(list) .filter(e -> e instanceof Number) .forEach(num -> processNumber((Number) num)); Here, the stream receives the list as a single element, so its elements are not processed individually. Use list.stream() when processing the collection contents. section 8.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the single-element consequence with a focused filtering example, but does not develop stream internals.
Examples
Uses Stream.of(list) with a number filter to show that the list itself, rather than its contents, enters the stream.
What it assumes
Assumes familiarity with Java collections and streams while clarifying their differing method inputs.
What you can do after
Diagnose accidental collection wrapping and choose collection.stream() when processing collection elements.
How it connects
Connects Stream.of with collection.stream(), List.of(), List.copyOf(), add(), and addAll().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.