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())
The toList() method of the Collectors class returns a Collector that accumulates the input elements into a new List.
For instance, Collectors. toList() method can return an ArrayList or a LinkedList or any other implementation of the List interface. To get the desired Collection, we can use the toCollection() method provided by the Collectors class.
The toList() method of Collectors Class is a static (class) method. It returns a Collector Interface that gathers the input data onto a new list. This method never guarantees type, mutability, serializability, or thread-safety of the returned list but for more control toCollection(Supplier) method can be used.
public interface LongStream extends BaseStream<Long,LongStream> A sequence of primitive long-valued elements supporting sequential and parallel aggregate operations. This is the long primitive specialization of Stream .
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With