Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect list of Long from Double stream in Java 8

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 interface java.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?

like image 870
aldrael Avatar asked Jun 11 '15 15:06

aldrael


People also ask

What does collect () do in Java?

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.

Which method can collect a stream in a custom collection?

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.

What does .stream do in Java?

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.


1 Answers

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 longs 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()); 
like image 194
Michael Avatar answered Oct 07 '22 22:10

Michael