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:
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
?
For most of the cases you should return Stream . It is more flexible, is designed for better performance, and can be easily turned into Collection . You should return Collection when there are strong consistency requirements and you have to produce snapshot of a moving target.
Get the stream of elements in which the duplicates are to be found. For each element in the stream, count the frequency of each element, using Collections. frequency() method. Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element.
Generating Streams With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.
I'm not saying you shouldn't return a Stream, and even less that you should never return a Stream, but doing it also has many disadvantages:
I would say that choosing to return a stream rather than a collection also depends on what you already have. If the collection is already materialized (think about a JPA entity having a OneToMany already materialized as a Set), I'd probably return an immutable wrapper over the collection. If, on the other hand, the collection to return is the result of a computation or transformation of another collection, returning a Stream might be a better choice.
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