Java 8 Stream 是安全的 return 类型吗?
Is Java 8 Stream a safe return type?
对于 public 方法,Java8 流是否安全 return 类型,因为给定流的基础对象不可能发生变异?
例如,如果我有一个 List
和 return list.stream();
是否可以使用 return 值以任何方式改变原始列表?
从 API 来看,我认为这不可能,但想确认一下。
是的,这样做是安全的。流 not/should 不会修改底层数据结构。
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).
来自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.
您可能还会看到 Non-interference。
[…] it would be impossible to mutate the underlying object given a stream from it.
虽然可能编写我们自己的实现修改底层数据结构的java.util.Stream
,但它会这样做是错误的。 ; )
回应@AlexisC 的评论:
Getting a stream from the list […] can modify its content if it contains mutable objects.
这是一个公平的观点。如果我们有一个 可变元素流,我们可以这样做:
myObj.stream().forEach(( Foo foo ) -> ( foo.bar = baz ));
对于 public 方法,Java8 流是否安全 return 类型,因为给定流的基础对象不可能发生变异?
例如,如果我有一个 List
和 return list.stream();
是否可以使用 return 值以任何方式改变原始列表?
从 API 来看,我认为这不可能,但想确认一下。
是的,这样做是安全的。流 not/should 不会修改底层数据结构。
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).
来自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.
您可能还会看到 Non-interference。
[…] it would be impossible to mutate the underlying object given a stream from it.
虽然可能编写我们自己的实现修改底层数据结构的java.util.Stream
,但它会这样做是错误的。 ; )
回应@AlexisC 的评论:
Getting a stream from the list […] can modify its content if it contains mutable objects.
这是一个公平的观点。如果我们有一个 可变元素流,我们可以这样做:
myObj.stream().forEach(( Foo foo ) -> ( foo.bar = baz ));