Difference LongStream VS Stream in Collectors.toList ()

Why, when I get the list from LongStream

with Collectors.toList()

, got an error, but Stream

there is no error with?

Examples:

MISTAKE:

Something.mapToLong(Long::parseLong).collect(Collectors.toList())

      

Right:

Something.map(Long::valueOf).collect(Collectors.toList())

      

+3


source to share


1 answer


The Stream API, there are four different classes: Stream

, IntStream

, LongStream

and DoubleStream

. The last three are used for the treatment of primitive values int

, long

and double

to increase productivity. They are adapted for these primitive types, and their methods are very different from those Stream

. For example, there is a method LongStream.sum()

, but there is no method Stream.sum()

, because you cannot sum any types of objects. Primitive streams do not work with collectors because collectors accept objects (there are no special primitive collectors in the JDK).

The class Stream

can be used to handle any object, including primitive wrapper classes such as Integer

, long

and double

. As you want to build in List<Long>

, you don't need a stream of long

primitives, but a stream of objects long

. So you need Stream<Long>

and map

instead of mapToLong

. mapToLong

might be useful, for example, if you need a primitive array long[]

:



long[] result = Something.mapToLong(Long::valueOf).toArray();

      

+2


source







All Articles