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.
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.
double doubleArray = longList.stream().mapToDouble(v -> v).toArray();
If you are using Java 8 try this:
list.stream().map(v -> (double)v) .toArray(Double::new);