-1

I want to convert a Double list to double array, and tried 2 ways (line 2 and 3), but line 3 can not pass compilation and reports an error:

Non-static method can not referenced from a static context

by IDEA tips.

when compiled by maven it report:

Incompatible type: invalid method reference.

List<Double> res = new ArrayList<>();
double[] doubles = res.stream().mapToDouble(Double::doubleValue).toArray();
Arrays.stream(res.toArray()).mapToDouble(Double::doubleValue).toArray();
Naman
  • 27,789
  • 26
  • 218
  • 353
zhangbing
  • 31
  • 6
  • Your question has already been answered. Here's one more method of doing the conversion from list to primitive array. `double[] doubles = ArrayUtils.toPrimitive(res.toArray(new Double[0]));` – fzn Nov 17 '19 at 08:01

1 Answers1

1

toArray() returns an Object[], so Arrays.stream(res.toArray()) returns a Stream<Object>.

You need to pass a Double[] to Arrays.stream() in order to get a Stream<Double>, which will allow you to map to double with Double::doubleValue:

Arrays.stream(res.toArray(new Double[res.size()])).mapToDouble(Double::doubleValue).toArray();

Your first Stream pipeline works, since res.stream() returns Stream<Double>.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    Preferably `new Double[0]` as stated in [this Q&A](https://stackoverflow.com/questions/174093/toarraynew-myclass0-or-toarraynew-myclassmylist-size). – Naman Nov 17 '19 at 07:59