Is Java 8 Stream a safe return type? -


are java 8 streams safe return types public methods, in impossible mutate underlying object given stream it?

for example, if have list , return list.stream(); return value in way used mutate original list?

judging api, don't think it's possible confirm.

yes, safe so. streams not/should not modify underlying data structure.

a few excerpts java.util.stream.stream:

a sequence of elements […].

collections , streams, while bearing superficial similarities, have different goals. collections concerned efficient management of, , access to, elements. contrast, streams not provide means directly access or manipulate elements […].

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

and package java.util.stream description:

streams differ collections in several ways:

  • no storage. a stream not data structure stores elements; instead, conveys elements source […], through pipeline of computational operations.
  • functional in nature. an operation on stream produces result, not modify source.

you might see non-interference.


[…] impossible mutate underlying object given stream it.

while possible write our own implementation of java.util.stream modified underlying data structure, error so. ; )


in response comment @alexisc.:

getting stream list […] can modify content if contains mutable objects.

this fair point. if have stream of elements mutable, can do:

myobj.stream().foreach(( foo foo ) -> ( foo.bar = baz )); 

Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -