default Stream<E> stream()
is added to Collection
interface to support streams in Java 8. Similar functionality is supported by public static<T> Stream<T> of(T t)
in Stream
class. What different purpose is static of() method solving ?
The method stream()
of the Collection
interface can be called on an existing collection. Being an interface method, it can be overridden by actual collection implementations to return a Stream
adapted to the specific collection type.
The standard collections of the JRE don’t take this opportunity, as the default implementation’s strategy of delegating to spliterator()
, which is also an overridable method, suits their needs. But the documentation even mentions scenarios in which the collection should override stream()
:
This method should be overridden when the spliterator() method cannot return a spliterator that is
IMMUTABLE
,CONCURRENT
, or late-binding.
In contrast, the static
factory method(s) Stream.of(…)
are designed for the case when you have a fixed number of elements without a specific collection. There is no need to create a temporary Collection
when all you want is a single Stream
over the elements you can enumerate.
Without collections of potentially different type, there is no need for overridable behavior, hence, a static
factory method is sufficient.
Note that even if you don’t have a enumerable fixed number of elements, there is an optimized solution for the task of creating a single stream, when no reusable collection is needed:
Stream.Builder<MyType> builder=Stream.builder();
builder.add(A);
if(condition) builder.add(B);
builder.add(C);
builder.build()./* stream operations */
As far as I can tell, of
is just an utility method to create Streams on the fly, without the need to wrap your elements inside a collection first.
Generally static factory methods as of
are provided to skip the array creation because of var-args. For example java-9 immutable collections provide many overloads of these methods like:
Set.of()
Set.of(E)
Set.of(E e1, E e2)
.... so on until 11
Set.of(E... elem)
Even the description of those methods is:
While this introduces some clutter in the API, it avoids array allocation, initialization, and garbage collection overhead that is incurred by varargs calls
Since there are only two methods in Stream:
Stream.of(T t)
Streamm.of(T ... values)
I consider that small utility methods that can create Streams from var-args
.
But they still provide a method that creates a Stream with a single element (instead of leaving just the var-args method), so for a single element this is already optimized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With