Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>.

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?

like image 608
gstackoverflow Avatar asked Oct 07 '15 14:10

gstackoverflow


People also ask

Does collectors toList return empty List?

Collector. toList() will return an empty List for you. As you can see ArrayList::new is being used as a container for your items.

What is collect collectors toList ())?

The toList() method of Collectors Class is a static (class) method. It returns a Collector Interface that gathers the input data onto a new list. This method never guarantees type, mutability, serializability, or thread-safety of the returned list but for more control toCollection(Supplier) method can be used.

What implementation of List does the collectors toList () create?

If you look at the documentation of Collectors#toList() , it states that - "There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned". If you want a particular implementation to be returned, you can use Collectors#toCollection(Supplier) instead.


1 Answers

You could use boxed(). This maps a DoubleStream (Stream of primitive doubles, as returned by mapToDouble) to a 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.

But why are you using mapToDouble to begin with? You could just use map like this:

Stream.of("1,2,3,4".split(",")).map(Double::valueOf).collect(Collectors.toList());
like image 193
Tunaki Avatar answered Oct 15 '22 17:10

Tunaki