Converting Primitive Long Arrays to List of Longs
Converting an array of primitive longs (long[]) to a List can be a straightforward yet puzzling task for Java programmers. The conventional approach of utilizing Arrays.asList() may not suffice, prompting the need for alternative solutions.
In this article, we explore a reliable approach to accomplish this conversion using Java 8 features:
Using Streams
With Java 8's stream functionality, converting primitive long arrays to List becomes a concise and efficient operation:
<code class="java">long[] arr = { 1, 2, 3, 4 };
List<Long> list = Arrays.stream(arr).boxed().collect(Collectors.toList());</code>
Here's how this solution works:
- Arrays.stream(arr) creates a stream from the primitive long array.
- boxed() converts the primitive long values in the stream to objects of type Long.
- Collectors.toList() collects the elements in the stream into a list.
By utilizing this approach, you can effectively transform an array of primitive longs into a List without facing compile-time errors or runtime exceptions.
The above is the detailed content of How to Convert a Primitive Long Array to a List of Longs in Java?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn