Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way of converting List<Long> object to long[] array in java?

Is there any utility method to convert a list of Numerical types to array of primitive type? In other words I am looking for a better solution than this.

private long[] toArray(List<Long> values) {     long[] result = new long[values.size()];     int i = 0;     for (Long l : values)         result[i++] = l;     return result; } 
like image 936
Yasin Bahtiyar Avatar asked May 30 '11 10:05

Yasin Bahtiyar


People also ask

How do you convert a list to an array in Java?

The best and easiest way to convert a List into an Array in Java is to use the . toArray() method. Likewise, we can convert back a List to Array using the Arrays. asList() method.

How would you convert a list to an array?

Create a List object. Add elements to it. Create an empty array with size of the created ArrayList. Convert the list to an array using the toArray() method, bypassing the above-created array as an argument to it.

What method is used to convert from an array to a list in Java?

Convert your array to a List with the Arrays. asList utility method. Integer[] numbers = new Integer[] { 1, 2, 3 }; List<Integer> list = Arrays. asList(numbers);


1 Answers

Since Java 8, you can do the following:

long[] result = values.stream().mapToLong(l -> l).toArray(); 

What's happening here?

  1. We convert the List<Long> into a Stream<Long>.
  2. We call mapToLong on it to get a LongStream
    • The argument to mapToLong is a ToLongFunction, which has a long as the result type.
    • Because Java automatically unboxes a Long to a long, writing l -> l as the lambda expression works. The Long is converted to a long there. We could also be more explicit and use Long::longValue instead.
  3. We call toArray, which returns a long[]
like image 99
robinst Avatar answered Sep 21 '22 14:09

robinst