Home >Java >javaTutorial >How to Convert a Primitive `long` Array to a `List` in Java?

How to Convert a Primitive `long` Array to a `List` in Java?

DDD
DDDOriginal
2024-10-30 18:15:02809browse

How to Convert a Primitive `long` Array to a `List` in Java?

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:

  • Arrays.stream(arr) creates a stream of primitive longs.
  • boxed() is a stream operation that transforms each primitive long to a Long object.
  • collect(Collectors.toList()) collects the Long objects into a list.

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!

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