gpt4 book ai didi

java - Collectors.toList() 返回什么样的 List

转载 作者:IT老高 更新时间:2023-10-28 20:21:24 25 4
gpt4 key购买 nike

我正在阅读 State of the Lambda: Libraries Edition ,并且对一个声明感到惊讶:

Streams 部分下,有以下内容:

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

文件没有说明shapes实际上是,我不知道这是否重要。

让我感到困惑的是:什么样的混凝土List这段代码会返回吗?

  • 它将变量分配给 List<Shape> ,完全没问题。
  • stream()也不是 filter()决定使用哪种列表。
  • Collectors.toList()两者都没有指定 List 的具体类型.

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

最佳答案

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

如果您查看 Collectors#toList() 的文档,它声明 - “不保证返回的列表的类型、可变性、可序列化性或线程安全性”。如果要返回特定的实现,可以使用 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));

关于java - Collectors.toList() 返回什么样的 List<E>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21912314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com