问题描述
在Java 8中,我越来越多地用 Stream
替换 Collection
返回值。
In Java 8 I am increasingly replacing Collection
return values with Stream
.
所以我曾经拥有过:
public List<Element> getElementList() {
return elements;
}
我现在正在使用:
public Stream<Element> streamElements() {
return elements.stream();
}
我的论点是:
- 它强制执行基础列表的不变性
- 它隐藏了是基础列表的事实。以后可以在不改变方法签名的情况下将其更改为集合或其他结构。
- 它很好地封装了该方法的用户应该对项目执行某些操作而不是使用列表。
- 如果需要,可以在以后简单地进行并行化。
- It enforces the immutability of the underlying list
- It hides the fact that there is an underlying list. It could later be changed to a set or some other structure without changing the method signature.
- It nicely encapsulates that the user of the method is expected to do something with the items not something with a list.
- It can be trivially parallelised later if required.
实际上现在,在我的代码,返回一个 List
或其他一些集合明确表示用户可能认为该集合是可变的,并且预计能够更改它。
In fact now, in my code, returning a List
or some other collection is explicitly a recognition that the user may consider the collection mutable and is expected to be able to change it.
显然,使用不可变集合可以实现其中一些。
Clearly some of this can be achieved with immutable collections.
我的问题是:任何人都可以看到这个设计的任何缺点吗?返回 Stream
?
My question is: can anyone see any disadvantages with this design? Are there any advantages of immutable collections over returning a Stream
?
推荐答案
是不可变集合的任何优点吗?我不是说你不应该返回Stream,更不要说你不应该返回Stream,但是这样做也有很多缺点:
I'm not saying you shouldn't return a Stream, and even less that you should never return a Stream, but doing it also has many disadvantages:
- 它不会告诉用户API是否订购(列表)或不订购(设置),或排序(排序设置)
- 它不会告诉用户API的用户,如果集合可以包含重复项(List)或不包含(Set)
- 它不允许用户轻松快速地访问列表的第一个或最后一个元素,或者甚至知道它有哪个尺寸。
- 如果API的用户需要对集合进行多次传递,他就不得不将每个元素复制到一个新的集合中。
- it doesn't tell the user of the API if the collection is ordered (List) or not (Set), or sorted (SortedSet)
- it doesn't tell the user of the API if the collection can contain duplicates (List) or not (Set)
- it doesn't allow the user to easily and quickly access the first or last element of the list, or even to know which size it has.
- if the user of the API needs to do multiple passes over the collection, he's forced to copy every element into a new collection.
我会说选择返回流而不是集合也取决于你已经拥有的东西。如果集合已经实现(考虑一个已经实现为OneToMany的JPA实体),我可能会在集合上返回一个不可变的包装器。另一方面,如果要返回的集合是计算或转换另一个集合的结果,则返回Stream可能是更好的选择。
I would say that choosing to return a stream rather than a collection also depends on what you already have. If the collection is already materialized (think about a JPA entity having a OneToMany already materialized as a Set), I'd probably return an immutable wrapper over the collection. If, on the other hand, the collection to return is the result of a computation or transformation of another collection, returning a Stream might be a better choice.
这篇关于返回流而不是列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!