How to convert a List< Long> into a double[] in Java

abhimanyue :

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.

assylias :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=10493&siteId=1