Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java 8 Stream a safe return type?

Are Java 8 Streams safe return types for public methods, in that it would be impossible to mutate the underlying object given a stream from it?

For example, if I have a List and return list.stream(); could the return value in any way be used to mutate the original list?

Judging from the API, I don't think it's possible but would like to confirm.

like image 589
arcyqwerty Avatar asked Apr 14 '15 21:04

arcyqwerty


1 Answers

Yes, it is safe to do so. Streams do not/should not modify the underlying data structure.

A few excerpts from java.util.stream.Stream:

A sequence of elements […].

Collections and streams, while bearing some superficial similarities, have different goals. Collections are primarily concerned with the efficient management of, and access to, their elements. By contrast, streams do not provide a means to directly access or manipulate their elements […].

To preserve correct behavior, [behavioral parameters to stream operations …] must be non-interfering (they do not modify the stream source).

And from Package java.util.stream Description:

Streams differ from collections in several ways:

  • No storage. A stream is not a data structure that stores elements; instead, it conveys elements from a source […], through a pipeline of computational operations.
  • Functional in nature. An operation on a stream produces a result, but does not modify its source.

You might also see Non-interference.


[…] it would be impossible to mutate the underlying object given a stream from it.

While it would be possible to write our own implementation of java.util.Stream that modified the underlying data structure, it would be an error to do so. ; )


In response to the comment by @AlexisC.:

Getting a stream from the list […] can modify its content if it contains mutable objects.

This is a fair point. If we have a stream of elements which are mutable, we can do:

myObj.stream().forEach(( Foo foo ) -> ( foo.bar = baz ));
like image 186
Radiodef Avatar answered Sep 19 '22 17:09

Radiodef