Collectors.toList()返回什么类型的 List < E > ?

我正在阅读 Lambda 状态: 图书馆版,有一句话让我感到惊讶:

小溪节中,有以下内容:

List<Shape> blue = shapes.stream()
.filter(s -> s.getColor() == BLUE)
.collect(Collectors.toList());

该文档没有说明 shapes实际上是什么,我甚至不知道它是否重要。

让我感到困惑的是: 这个代码块返回什么样的具体 List

  • 它将变量赋值给 List<Shape>,这完全没问题。
  • stream()filter()决定使用什么类型的列表。
  • Collectors.toList()既不指定 List的具体类型。

那么,这里使用的 List混凝土类型(子类)是什么? 有什么保证吗?

73591 次浏览

It doesn't matter, but the concrete type is non-generic as indeed all types are non-generic at runtime.

So, what concrete type (subclass) of List is being used here? Are there any guarantees?

I don't think so, but ArrayList or LinkedList seem likely.

So, what concrete type (subclass) of List is being used here? Are there any guarantees?

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

And from the lambda, you can return whatever implementation you want of List<Shape>.

Update:

Or, you can even use method reference:

List<Shape> blue = shapes.stream()
.filter(s -> s.getColor() == BLUE)
.collect(Collectors.toCollection(LinkedList::new));

Navigating through Netbeans (Ctrl + Click), I landed in this code. It seems to be using an ArrayList as Supplier.

public static <T> Collector<T, ?, List<T>> toList() {
return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
(left, right) -> { left.addAll(right); return left; },
CH_ID);
}