How to put DoubleStream into a list

I have the following code:

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

I want to return a List<Double> .

This code does not compile.

I see an 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 problem?

+7
java java-8 java-stream collect
source share
1 answer

You can use boxed() . This maps a DoubleStream (stream of primitive doubles returned by mapToDouble ) to 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 Double from returning to Double.valueOf to be unboxed with primitive Double .

But why are you using mapToDouble for a start? You can simply use map as follows:

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

All Articles