Convert an array of primitive longs into a List of Longs
How to convert a long[]
to List<Long>
quickly using Java 8 Streams?
Magic potion: Arrays.stream
to get stream, .boxed()
to wrap each long
to Long
, .collect(Collectors.toList())
to create a final List<Long>
.
In-depth study: Understand the nuances
Master the art of converting an array of long
type into a List<Long>
. Let's dive into the details:
Boxing: The art of wrapping!
boxed()
method in Streams acts as a magician converting the characters(primitives) from long
to Long
. It's like wrapping chocolates in colorful papers!
ArrayList Initialization Hacker-Style
When you know the length of the array, you don't want to put extra load on garbage collection. prefixing the ArrayList
size can save unnecessary memory allocations - A hack known only to pros.
Handing large arrays: Go Lazy or Go Home
With the rise in popularity of lazy evaluation (think Haskell), streams can be a lifesaver. Streams are lazy, they don't calculate values until they are absolutely necessary. With large long
arrays, going lazy can help you save memory.
The Commons Lang way
Apache to the rescue! If your project already uses Apache Commons Lang, you can use ArrayUtils.toObject()
to make your life easier.
Detour: Alternatives and how to use them
Old-school loop addition
Not everyone likes to sit on the fast lane. For developers who prefer to steer clear of shortcuts and take the traditional route:
List to Array: A Twist in the Tale
Reversing the conversion is as easy as reversing a String (well almost). To convert List<Long>
back into long[]
:
Beware of Type Incompatibility
Remember how Prince Charming could not fit his glass slipper(size and shape) on anybody but Cinderella(direct match)? Using Arrays.asList()
directly on a primitive array would be like trying to fit a square peg in a round hole.
Mastering Conversion Nuances
Loopholes in Autoboxing 🔍
Manually initiating autoboxing could be slightly performant over implicit conversion.
Multicore Performance with Parallel Streams 🚀
For large datasets execution can be divided on multiple cores. However, remember unlike Autobots, CPUs do not assemble (combine results) automatically! Hence, synchronization plays a crucial role post execution.
Permanent Immutable Art: Unmodifiable List 🏺
Some lists are not meant to be tampered with. They are more like pieces of immutable art. Each modification needs a new piece. Hence, Collections.unmodifiableList
comes to the rescue.
Was this article helpful?