[英]How to collect DoubleStream to List
I have the following code: 我有以下代码:
Stream.of("1,2,3,4".split(",")).mapToDouble(Double::valueOf).collect(Collectors.toList());
I want to return List<Double>
. 我想返回List<Double>
。
This code doesn't compile. 此代码无法编译。
I see error: 我看到错误:
Error:(57, 69) java: method collect in interface java.util.stream.DoubleStream cannot be applied to given types;
required: java.util.function.Supplier<R>,java.util.function.ObjDoubleConsumer<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)
How to fix this issue? 如何解决这个问题?
You could use boxed()
. 你可以使用boxed()
。 This maps a DoubleStream
(Stream of primitive doubles, as returned by mapToDouble
) to a Stream<Double>
. 这将DoubleStream
(原始双精度流,由mapToDouble
返回) mapToDouble
到Stream<Double>
。
Stream.of("1,2,3,4".split(",")).mapToDouble(Double::parseDouble).boxed().collect(Collectors.toList());
Note that I changed Double::valueOf
to Double::parseDouble
: this prevents the Double
returned by Double.valueOf
to be unboxed to the primitive double
. 请注意,我将Double::valueOf
更改为Double::parseDouble
:这可以防止Double.valueOf
返回的Double
被取消装箱到原始double
。
But why are you using mapToDouble
to begin with? 但是你为什么要开始使用mapToDouble
? You could just use map
like this: 您可以像这样使用map
:
Stream.of("1,2,3,4".split(",")).map(Double::valueOf).collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.