简体   繁体   English

Java 8 Stream是安全的返回类型吗?

[英]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? Java 8 Streams是否是公共方法的安全返回类型,因为在给定流的基础对象时不可能改变它?

For example, if I have a List and return list.stream(); 例如,如果我有一个Listreturn 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. 从API来看,我认为这不可能,但我想确认一下。

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 : 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 : 并从Package java.util.stream描述

Streams differ from collections in several ways: Streams在几个方面与集合不同:

  • 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. 虽然可以编写我们自己java.util.Stream实现来修改底层数据结构,但这样做是错误的。 ; ; )


In response to the comment by @AlexisC.: 回应@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 ));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM