Home » Java » arrays – How to convert a List< Long> into a double[] in Java-Exceptionshub

arrays – How to convert a List< Long> into a double[] in Java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am trying to convert a List<Long> to a double[] in Java,

I did in the following way,

  List<Long> longList = ........;

  int len = longList.size();

  double[] doubleArray = new double[len];

  for (int i = 0; i < len; i++)
     doubleArray[i] = (double) longList.get(i);

I am wondering if I can do it in a smarter way (and how) since I’m using Java-8, I saw some conversion using the stream method. But couldn’t find anything that can solve my problem.

How to&Answers:

You could indeed do it using a stream:

double[] result = longList.stream()
                          .mapToDouble(Long::doubleValue)
                          .toArray();

It’s maybe a little shorter and cleaner but you won’t gain anything performance wise.

Answer:

Just use:

double[] doubleArray = longList.stream().mapToDouble(v -> v).toArray();

Answer:

If you are using Java 8 try this:

list.stream().map(v -> (double)v)
    .toArray(Double[]::new);