我有以下代码:
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());
这段代码不起作用,编译错误是:
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)
我已经尝试了很多收集器的用法,但我仍然无法使其工作。 我做错了什么?
最佳答案
mapToLong
给你一个 LongStream
这不可能是 collect
-编辑者 Collectors.toList
.
这是因为 LongStream
是
A sequence of primitive long-valued elements
我们不能有 List<long>
,我们需要一个 List<Long>
.因此,为了能够收集它们,我们首先需要将这些原始 long
装箱。转入 Long
对象:
list.stream().map(i -> i * 2.5)
.mapToLong(Double::doubleToRawLongBits)
.boxed() //< I added this line
.collect(Collectors.toList());
boxed
方法给我们一个Stream<Long>
我们可以将其收集到一个列表中。
使用 map
而不是 mapToLong
也将起作用,因为这将导致 Steam<Long>
其中值自动装箱:
list.stream().map(i -> i * 2.5)
.map(Double::doubleToRawLongBits)
.collect(Collectors.toList());
关于java - 从 Java 8 中的 Double 流中收集 Long 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30785278/