I have the following code:
List<Long> list = new ArrayList<>(); list.add(4L); list.add(92L); list.add(100L); List<Long> newList = list.stream().map(i -> i * 2.5) .mapToLong(Double::doubleToRawLongBits) .collect(Collectors.toList());
This code doesn't work and the compilation error is:
method
collect
in interfacejava.util.stream.LongStream
cannot be applied to given types;
required:java.util.function.Supplier<R>,java.util.function.ObjLongConsumer<R>,java.util.function.BiConsumer<R,R>
found:java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.List<java.lang.Object>>
reason: cannot infer type-variable(s)R
(actual and formal argument lists differ in length)
I have tried many usages of Collectors but I still can't make it to work. What am I doing wrong?
Java Stream collect() is mostly used to collect the stream elements to a collection. It's a terminal operation. It takes care of synchronization when used with a parallel stream. The Collectors class provides a lot of Collector implementation to help us out.
Stream to Collection using Collectors. toCollection() You can also collect or accumulate the result of Stream processing into a Collection of your choices like ArrayList, HashSet, or LinkedList. There is also a toCollection() method in the Collectors class that allows you to convert Stream to any collection.
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
mapToLong
gives you a LongStream
which is not able to be collect
-ed by Collectors.toList
.
This is because LongStream
is
A sequence of primitive long-valued elements
We can't have a List<long>
, we need a List<Long>
. Therefore to be able to collect them we first need to box these primitive long
s into Long
objects:
list.stream().map(i -> i * 2.5) .mapToLong(Double::doubleToRawLongBits) .boxed() //< I added this line .collect(Collectors.toList());
The boxed
method gives us a Stream<Long>
which we're able to collect to a list.
Using map
rather than mapToLong
will also work because that will result in a Steam<Long>
where the values are automatically boxed:
list.stream().map(i -> i * 2.5) .map(Double::doubleToRawLongBits) .collect(Collectors.toList());
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