[英]Difference LongStream VS Stream in Collectors.toList()
Why when I am getting a list from a LongStream
with Collectors.toList()
got an error but with Stream
there is no error? 为什么当我从具有
Collectors.toList()
的LongStream
获取列表时出现错误,但是使用Stream
时没有错误?
Examples : 例子 :
ERROR : 错误:
Something.mapToLong(Long::parseLong).collect(Collectors.toList())
Correct : 正确:
Something.map(Long::valueOf).collect(Collectors.toList())
There are four distinct classes in Stream API: Stream
, IntStream
, LongStream
and DoubleStream
. Stream API中有四个不同的类:
Stream
, IntStream
, LongStream
和DoubleStream
。 The latter three are used to process the primitive values int
, long
and double
for better performance. 后三者用于处理原始值
int
, long
和double
以获得更好的性能。 They are tailored for these primitive types and their methods differ much from the Stream
methods. 它们是针对这些原始类型而定制的,它们的方法与
Stream
方法有很大不同。 For example, there's a LongStream.sum()
method, but there's no Stream.sum()
method, because you cannot sum any types of objects. 例如,有一个
LongStream.sum()
方法,但是没有Stream.sum()
方法,因为你不能对任何类型的对象求和。 The primitive streams don't work with collectors as collectors are accepting objects (there are no special primitive collectors in JDK). 由于收集器正在接受对象(JDK中没有特殊的原始收集器),原始流不能与收集器一起使用。
The Stream
class can be used to process any objects including primitive type wrapper classes like Integer
, Long
and Double
. Stream
类可用于处理任何对象,包括原始类型包装类,如Integer
, Long
和Double
。 As you want to collect to the List<Long>
, then you don't need a stream of long
primitives, but stream of Long
objects. 如果要收集到
List<Long>
,则不需要long
基元流,而是需要Long
对象流。 So you need Stream<Long>
and map
instead of mapToLong
. 所以你需要
Stream<Long>
和map
而不是mapToLong
。 The mapToLong
can be useful, for example, if you need a primitive long[]
array: mapToLong
可能很有用,例如,如果你需要一个原始的long[]
数组:
long[] result = Something.mapToLong(Long::valueOf).toArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.