How to Convert a Primitive long Array to a List of Longs
When working with Java arrays, it's common to encounter scenarios where you need to convert a primitive array to a list of objects. This particular question centers around transforming an array of primitive longs to a List of Longs.
The Unsuccessful Attempt
The initial attempt to convert the array using Arrays.asList(input) failed because this method expects an object array as an argument. Since Java primitive types like long are not objects, attempting to pass a primitive array resulted in the compilation error.
The Solution Using Streams
With Java 8, streams provide an efficient way to handle such conversions. Using the stream API, the conversion can be achieved as follows:
<code class="java">long[] arr = { 1, 2, 3, 4 }; List<Long> list = Arrays.stream(arr) .boxed() .collect(Collectors.toList());</code>
Explanation:
This approach ensures that the primitive long array is converted to a List of Longs, meeting the requirement of having a collection of object references.
The above is the detailed content of How to Convert a Primitive `long` Array to a `List` in Java?. For more information, please follow other related articles on the PHP Chinese website!