Home > Net >  How to collect a list of doubles from a stream?
How to collect a list of doubles from a stream?

Time:02-28

say I desire to collect a list of doubles[] from a lambda function, I have created the following example, however it do not compile given the type. What could I do as a workaround?

public class CollectingStreams {
    public static double [] methodReturnArray(int n){
        return new double[] {1*n,2*n};
    }
    public static void main(String[] args){

        List<double[]> listArray= IntStream.range(0,5).parallel().forEach(
                (n) -> {methodReturnArray(n).collect(Collectors.toList());
                });
    }
}

Here is the compilation error:

java: cannot find symbol
  symbol:   method collect(java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.List<java.lang.Object>>)
  location: class double[]

As an attempt I have tried the following

        List<double[]> listArray= IntStream.range(0,5).parallel().forEach(
                (n) -> {
                    Arrays.stream(methodReturnArray(n)).collect(Collectors.toList());
                });

However it prompts this compilation error:

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)

Moreover I have seen (here)[https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html] that fiven side effects it is best to avoid arrays favoring collecting to lists, therefore I must use Arrays with care.

I am not sure exactly how to properly cast or modify my attempts do that I can collect my list of double[].

Any thoughts?

Thanks

CodePudding user response:

Instead of the .forEach() use .mapToObject(), as forEach doesn't return anything that could be processed further.

This is the code I would try:

List<double[]> listArray = IntStream.range(0,5)
    .mapToObj(CollectingStreams::methodReturnArray)
    .collect(Collectors.toList());

CodePudding user response:

List<int> numbers = new ArrayList<>();
List<double> numbers.stream().map(number -> (double) number).toList();
  • Related