Collect list of Long from Double stream in Java 8

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());

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)