问答 百科手机端

什么样的清单 收集器 清单()返回?

2023-04-29 12:39

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

如果查看的文档Collectors#toList ,它会指出-“无法保证返回的List的类型,可变性,可序列化性或线程安全性” 。如果要返回特定的实现,则可以Collectors#toCollection(Supplier)改用。

supplier<List<Shape>> supplier =   -> new LinkedList<Shape> ;

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

从lambda中,您可以返回所需的任何实现List<Shape>

或者,您甚至可以使用方法参考:

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

解决方法

我正在阅读Lambda的状态:图书馆版,并对以下声明感到惊讶:

Streams 部分下,有以下内容:

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

该文件没有说明shapes实际的内容,我也不知道它是否重要。

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

  • 它将变量分配给List<Shape>,这是完全可以的。
  • stream 也不filter 决定要使用哪种列表。
  • Collectors.toList 均未指定的具体类型List

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

热门