Reputation: 123
Why when I am getting a list from a LongStream
with Collectors.toList()
got an error but with Stream
there is no error?
Examples :
ERROR :
Something.mapToLong(Long::parseLong).collect(Collectors.toList())
Correct :
Something.map(Long::valueOf).collect(Collectors.toList())
Upvotes: 9
Views: 5779
Reputation: 100199
There are four distinct classes in Stream API: Stream
, IntStream
, LongStream
and DoubleStream
. The latter three are used to process the primitive values int
, long
and double
for better performance. They are tailored for these primitive types and their methods differ much from the Stream
methods. For example, there's a LongStream.sum()
method, but there's no Stream.sum()
method, because you cannot sum any types of objects. The primitive streams don't work with collectors as collectors are accepting objects (there are no special primitive collectors in JDK).
The Stream
class can be used to process any objects including primitive type wrapper classes like Integer
, Long
and 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. So you need Stream<Long>
and map
instead of mapToLong
. The mapToLong
can be useful, for example, if you need a primitive long[]
array:
long[] result = Something.mapToLong(Long::valueOf).toArray();
Upvotes: 16