问题描述
我正在阅读Lambda 现状:图书馆版,并且我对一个声明感到惊讶:
I am reading State of the Lambda: Libraries Edition, and am being surprised by one statement:
在 Streams 部分下,有以下内容:
Under the section Streams, there is the following:
List<Shape> blue = shapes.stream()
.filter(s -> s.getColor() == BLUE)
.collect(Collectors.toList());
文档没有说明 shapes
实际上是什么,我不知道它是否重要.
The document does not state what shapes
actually is, and I do not know if it even matters.
令我困惑的是:这段代码返回什么样的具体List
?
What confuses me is the following: What kind of concrete List
does this block of code return?
- 它将变量分配给一个
List
,这完全没问题. stream()
和filter()
决定使用哪种列表.Collectors.toList()
均未指定List
的具体类型.
- It assigns the variable to a
List<Shape>
, which is completely fine. stream()
norfilter()
decide what kind of list to use.Collectors.toList()
neither specifies the concrete type ofList
.
那么,这里使用了 List
的什么具体类型(子类)?有什么保证吗?
So, what concrete type (subclass) of List
is being used here? Are there any guarantees?
推荐答案
如果您查看 Collectors#toList()
,它指出 - 没有对类型、可变性、可序列化或线程的保证- 返回列表的安全性".如果您希望返回特定的实现,您可以使用 Collectors#toCollection(Supplier)
.
If you look at the documentation of Collectors#toList()
, it states that - "There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned". If you want a particular implementation to be returned, you can use Collectors#toCollection(Supplier)
instead.
Supplier<List<Shape>> supplier = () -> new LinkedList<Shape>();
List<Shape> blue = shapes.stream()
.filter(s -> s.getColor() == BLUE)
.collect(Collectors.toCollection(supplier));
从 lambda 中,你可以返回任何你想要的 List
实现.
And from the lambda, you can return whatever implementation you want of List<Shape>
.
更新:
或者,你甚至可以使用方法引用:
Or, you can even use method reference:
List<Shape> blue = shapes.stream()
.filter(s -> s.getColor() == BLUE)
.collect(Collectors.toCollection(LinkedList::new));
这篇关于什么样的列表<E>Collectors.toList() 会返回吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!