如何收集双流列表

2022-09-02 20:13:33

我有以下代码:

Stream.of("1,2,3,4".split(",")).mapToDouble(Double::valueOf).collect(Collectors.toList());

我想回来。List<Double>

此代码不编译。

我看到错误:

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)

如何解决此问题?


答案 1

您可以使用 boxed()。这会将 a(由 mapToDouble 返回的基元双精度流)映射到 .DoubleStreamStream<Double>

Stream.of("1,2,3,4".split(",")).mapToDouble(Double::parseDouble).boxed().collect(Collectors.toList());

请注意,我将 Double::valueOf 更改为 Double::p arseDouble:这可以防止返回的 by 被解装到基元 。DoubleDouble.valueOfdouble

但是,您为什么一开始就使用呢?你可以像这样使用:mapToDoublemap

Stream.of("1,2,3,4".split(",")).map(Double::valueOf).collect(Collectors.toList());

答案 2

推荐