什么样的List< E> Collectors.toList()会返回吗? [英] What kind of List<E> does Collectors.toList() return?

查看:309
本文介绍了什么样的List< E> Collectors.toList()会返回吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Lambda:Libraries Edition ,以及我对一个声明感到惊讶:

I am reading State of the Lambda: Libraries Edition, and am being surprised by one statement:

Streams 部分,有以下内容:

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

该文件未说明实际形状是的,我不知道它是否重要。

The document does not state what shapes actually is, and I do not know if it even matters.

令我困惑的是:什么样的具体列表这段代码是否返回?

What confuses me is the following: What kind of concrete List does this block of code return?


  • 它将变量分配给 List< Shape> ,这完全没问题。

  • stream()也不是 filter()决定使用哪种列表。

  • Collectors.toList()既未指定<$ c的具体类型$ c>列表。

  • It assigns the variable to a List<Shape>, which is completely fine.
  • stream() nor filter() decide what kind of list to use.
  • Collectors.toList() neither specifies the concrete type of List.

那么,具体类型(子类)这里使用 List ?有没有保证?

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

推荐答案


那么,正在使用List的具体类型(子类)这里?有保证吗?

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

如果你看一下 收集器#toList() ,它声明 - 返回的List的类型,可变性,可序列化或线程安全性没有保证。如果要返回特定实现,可以使用 收集者#toCollection(供应商)

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

这篇关于什么样的List&lt; E&gt; Collectors.toList()会返回吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆