In Java 8 I am increasingly replacing Collection
return values with Stream
.
So where I would once have had:
public List<Element> getElementList() {
return elements;
}
I am now using:
public Stream<Element> streamElements() {
return elements.stream();
}
My arguments for this are:
- It enforces the immutability of the underlying list
- It hides the fact that there is an underlying list. It could later be changed to a set or some other structure without changing the method signature.
- It nicely encapsulates that the user of the method is expected to do something with the items not something with a list.
- It can be trivially parallelised later if required.
In fact now, in my code, returning a List
or some other collection is explicitly a recognition that the user may consider the collection mutable and is expected to be able to change it.
Clearly some of this can be achieved with immutable collections.
My question is: can anyone see any disadvantages with this design? Are there any advantages of immutable collections over returning a Stream
?