gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:26:39 26 4
gpt4 key购买 nike

对于公共(public)方法,Java 8 Streams 的返回类型是否安全,因为在给定流的情况下不可能改变底层对象?

例如,如果我有一个 Listreturn list.stream(); 可以使用任何方式的返回值来改变原始列表吗?

从 API 来看,我不认为这是可能的,但想确认一下。

最佳答案

是的,这样做是安全的。流不会/不应修改底层数据结构。

摘录自 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).

来自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 ));

关于java - Java 8 Stream 是安全的返回类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29637726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com