<分区>
我了解到 Java 8 Stream 提供了 .collect
方法来将 Stream 转换为我们选择的任何集合/数据结构,它本质上是非常通用的。了解 Stream 可能源自非集合对象/资源。但是从使用的角度来看,将 Stream 转换为 List/Set 是很自然的。
Stream 已经提供了toArray()
方法来转换为数组,为什么不提供toList()
和toSet()
呢?
<分区>
我了解到 Java 8 Stream 提供了 .collect
方法来将 Stream 转换为我们选择的任何集合/数据结构,它本质上是非常通用的。了解 Stream 可能源自非集合对象/资源。但是从使用的角度来看,将 Stream 转换为 List/Set 是很自然的。
Stream 已经提供了toArray()
方法来转换为数组,为什么不提供toList()
和toSet()
呢?
最佳答案
因为你不知道 List
的实现是什么样的:
事实上,even Collectors.toList()
makes no guarantee :
There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).
因此,提供一个通用的 .toList()
方法将适合某些人的某些用法,但它永远无法适合所有人的所有用法。当然,这同样适用于 Collectors.toSet()
。
然而,数组不是问题:您知道可以用它们做什么。
关于java - 为什么 toList() 不直接在 Java 8 Stream 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31501406/